in reply to hashes with multiple values per key
Hi
To your first question: you can have multiple values per key by using an array reference as the value:
my (@keys, @values1, @values2); my %hash; for (0 .. $#keys) { $hash{$keys[$_]} = [ $values1[$_], $values2[$_] ]; }
A more compact method would use an hash slice and map:
@hash{ @keys } = map { [ $values1[$_], $values2[$_] ] } 0 .. $#values1 +;
Now, for a give key, here is how you can get the values:
# Return as an array: @values = @{ $hash{ $key } }; print $values[0]; # Return as an array ref: $values = $hash{ $key }; print $values->[0];
As for your second question: you can use a hash slice, again, to fetch a list of values based on a list of keys:
@values = @hash{ @keys }; for (@values) { print $_->[0], $_->[1]; }
A very important thing with this is watch the sigils (i.e. $, @, %) very closely.
perldata has information about hashes and subscripts.
perlref has information about references and dereferencing.
Ted Young
($$<<$$=>$$<=>$$<=$$>>$$) always returns 1. :-)
|
|---|