Key value pairs into scalar and array

Key value pairs into scalar and array

am 20.07.2006 23:07:35 von Tom Benett

Hello!

I've begun to learn perl, but doing some coding I always stuck at a problem.
I have a textfile in which I have these key / value pairs:

cycle = 2
car = 1
car = 3
car = 3
...

I'd like to put the value of key "cycle" into $a and the values of key "car"
into @b. Not into hash.
In which way I can do it? Should I slurp the entire file or read line by
line?

Thank you,
Tom

Re: Key value pairs into scalar and array

am 21.07.2006 00:12:12 von Joe Smith

Tom Benett wrote:
> Hello!
>
> I've begun to learn perl, but doing some coding I always stuck at a problem.
> I have a textfile in which I have these key / value pairs:
>
> cycle = 2
> car = 1
> car = 3
> car = 3
> ..
>
> I'd like to put the value of key "cycle" into $a and the values of key "car"
> into @b. Not into hash.

Why not do both?

linux% cat test2.pl
my %data;
while () {
if (my($key,$val) = /(\S+)\s*=\s*(.*)/) {
push @{$data{$key}},$val;
}
}

print "$_ = [@{$data{$_}}]\n" foreach sort keys %data;;
__DATA__
cycle = 2
car = 1
car = 3
car = 3

linux% perl test2.pl
car = [1 3 3]
cycle = [2]

In this case, $data{'cycle'} is a reference to a single-element array,
instead of a scalar, but it make things consistent.
-Joe