Key value pairs into scalar and array

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 [at] 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
Tom Benett [ Do, 20 Juli 2006 23:07 ] [ ID #1399188 ]

Re: Key value pairs into scalar and array

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 [at] b. Not into hash.

Why not do both?

linux% cat test2.pl
my %data;
while (<DATA>) {
if (my($key,$val) = /(\S+)\s*=\s*(.*)/) {
push [at] {$data{$key}},$val;
}
}

print "$_ = [ [at] {$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
Joe Smith [ Fr, 21 Juli 2006 00:12 ] [ ID #1399189 ]
Perl » alt.perl » Key value pairs into scalar and array

Vorheriges Thema: Help Needed for Web Based Directory Browser
Nächstes Thema: how to program in perl under windows?