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:  <%-{-{-{-<


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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.