Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: Multiple values assigned to same key in hashes

by AnomalousMonk (Archbishop)
on Feb 11, 2016 at 17:10 UTC ( [id://1154992]=note: print w/replies, xml ) Need Help??


in reply to Multiple values assigned to same key in hashes

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:

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 = {};
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 @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 ] };
(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.)


Give a man a fish:  <%-{-{-{-<

Replies are listed 'Best First'.
A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1154992]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-26 00:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found