123 123 - 1 month ago 7
Linux Question

Why are hash values being printed twice

Problem



Hash values are printed twice in for(each) loop.




Code



use strict;
use warnings;

my %Hash;

my $x=1;

foreach my $item( 1..9 ) {
$Hash{$x} = $x;
print scalar keys %Hash,",$item,",$x++,"\n"
}
$x=1;
foreach my $iteml( %Hash){
print $x++,"\n";
print "||||$iteml------$Hash{$iteml}||||\n";
}

print "@{[%Hash]}\n";





Output



1,1,1
2,2,2
3,3,3
4,4,4
5,5,5
6,6,6
7,7,7
8,8,8
9,9,9
1
||||6------6||||
2
||||6------6||||
3
||||3------3||||
4
||||3------3||||
5
||||7------7||||
6
||||7------7||||
7
||||9------9||||
8
||||9------9||||
9
||||2------2||||
10
||||2------2||||
11
||||8------8||||
12
||||8------8||||
13
||||1------1||||
14
||||1------1||||
15
||||4------4||||
16
||||4------4||||
17
||||5------5||||
18
||||5------5||||
6 6 3 3 7 7 9 9 2 2 8 8 1 1 4 4 5 5





Question



Why is this happening?




Version



v5.10.0 built for x86_64-linux-thread-multi

Answer

For one, you iterate over the hash itself, (%Hash). So you are getting keys and values, the list.

What makes it interesting is that the hash has the same keys and values. So it prints the key and its value, which is the same. Then it prints the value, and takes the value for that number as the key ... which is a valid key, and with the same value. So it looks like it prints twice :)

Comments