http://www.perlmonks.org?node_id=432254


in reply to Looping through a hash where some keys are the same

Does anyone else find it surprising that each returns twice? I would have thought that the second assignment of the duplicate key would overwrite the original, and you only get one key/value pair back.

I appeal to the wise among you...

#!/usr/bin/perl use Data::Dumper; my %h = ( a => 1, a => 2 ); print Dumper \%h; for ( my($k,$v) = each %h ) { print "$k -> $v\n"; } __END__ $VAR1 = { 'a' => 2 }; a -> 2 a -> 2 # why?

Replies are listed 'Best First'.
Re^2: Looping through a hash where some keys are the same
by lidden (Curate) on Feb 18, 2005 at 10:42 UTC
    each is returning a two element list, hence it is looping two times and $k, $v is only set once. It works as expected with a while. See "perldoc -f each".

      I new I was overlooking something obvious - thanks.