Just wondering if I am doing something wrong or if this is a perl bug…I want to create an array of hash values. I am using ‘push’ to put the values onto the array. The first write of a hash to the array works fine, but when I push a second different hash onto the array, the first array element seems to get overwritten with what I just pushed onto the array. Why is this happening? See code below:
use Data::Dumper;
my %val;
%val = (key1 => "Val1");
my @myArr;
my $cnt = push(@myArr,\%val);
print "After push (should contain 1 element): " . Dumper(@myArr) . "\n";
%val = (key2 => "Val2");
my $cnt = push(@myArr,\%val);
print "After push 2: (should contain 2 different elements):" . Dumper(@myArr) . "\n";
print " You can see above that element 1 and 2 of the array equal each other when they should be different\n";
“perl bug” – yeah, fat chance. 🙂
You’re pushing a reference to a hash into your array, then changing that very hash, and then you are pushing the same reference once again.
You probably need a copy or a whole different hash:
Different variable:
Copying: