This code is working for one and not for the other. ... The array in the two cases mentioned is different.
I, too, don't understand just what you want to achieve, and I'm confused by your reference to "two cases."
However, there is a small problem in your OPed code (as cleaned up by Random_Walk above) that can be illustrated by the following dataset:
The while-loop conditional it testing the truth of the "key" being shifted out of the array, but a false string can still be a valid hash key. A better approach might be something like:c:\@Work\Perl>perl -wMstrict -le "use Data::Dumper; my %hash; my @data = ('0', 'zero', 'foo',1, 'bar',2, 'foo',3, 'baz',4); while (my $key = shift @data) { my $value = shift @data; push @{$hash{$key}}, $value; } print Dumper \%hash " $VAR1 = {};
(Of course, this doesn't address the fact that the undefined value can be an element of the @data array and end up as a key (update: or hash value), but that's another story.)c:\@Work\Perl>perl -wMstrict -le "use Data::Dumper; ;; my @data = ('0', 'zero', 'foo',1, 'bar',2, 'foo',3, 'baz',4); ;; my %hash; while (@data) { my $k = shift @data; die qq{no value for key '$k'} unless @data; my $v = shift @data; push @{$hash{$k}}, $v; } print Dumper \%hash " $VAR1 = { 'bar' => [ 2 ], 'baz' => [ 4 ], '0' => [ 'zero' ], 'foo' => [ 1, 3 ] };
Give a man a fish: <%-{-{-{-<
In reply to Re: Multiple values assigned to same key in hashes
by AnomalousMonk
in thread Multiple values assigned to same key in hashes
by achs
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |