in reply to Re^3: How to assign an array to a value in hash?
in thread Re: How to assign an array to a value in hash?
Please, use strict, use warnings, and format/indent your code properly. You'll save yourself a LOT of headaches that way.
Now, that said, a hash can by its very nature only contain one value for the same key. So simply assigning to the same key more than once won't work, as you'll just overwrite any old value that might previously have been associated with that key.
However, the value can be a reference to an array (or any data structure, really). perldsc has more information on this, but here's how I might do it:
#!/usr/bin/perl use strict; use warnings; use feature qw/say/; my %parsed = (); while(<DATA>) { chomp; my ($key, $values) = split "=", $_, 2; my @values = split ",", $values; $parsed{$key} = \@values; } foreach my $key (sort keys %parsed) { say "$key: "; foreach my $value (@{ $parsed{$key} }) { say "\t$value"; } } __DATA__ key1=value1 key2=value2,value3,value4,value4,value5,value6,value7,value8,value9,va +lue10 key3=value11,value12
This outputs:
$ perl 1119309.pl key1: value1 key2: value2 value3 value4 value4 value5 value6 value7 value8 value9 value10 key3: value11 value12 $
The crucial lines here are the following two:
$parsed{$key} = \@values; # ... foreach my $value (@{ $parsed{$key} }) {
The first of these takes a reference to @values (using the \ operator); the second takes the reference stored in $parsed{$key} and dereferences it, i.e. converts it back to to an array, by using the @{ ... } circumfix construct. (Since @ is the array sigil, this can mnemonically be thought of as encapsulating a certain something and presenting it as an array on the outside.)
I hope this'll get you started! If you have further questions, just ask.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: How to assign an array to a value in hash?
by vukotid (Initiate) on Mar 09, 2015 at 12:31 UTC | |
by AppleFritter (Vicar) on Mar 09, 2015 at 21:23 UTC | |
by vukotid (Initiate) on Mar 10, 2015 at 04:48 UTC | |
by AppleFritter (Vicar) on Mar 10, 2015 at 09:40 UTC | |
by vukotid (Initiate) on Mar 17, 2015 at 04:47 UTC | |
|