in reply to Array of Hashes question
If %player is declared outside of the while loop, you're using the same hash for each iteration so when you push the hashref onto the array, you're pushing a ref to the same %player each time. Therefore, you end up with an array filled with hashrefs all referring to the same hash, and that is why all of the hashrefs have the same values. If you want to push a new hashref each time, declare a new hash inside the while loop.
Here is some code to illustrate the difference between declaring the hash outside of the loop vs declaring it inside the loop:
@array_out is filled with refs to the same hash, but each ref in @array_in is unique.use strict; use warnings; my ( %outhash, @array_out, @array_in ); for( my $i = 0; $i < 5; $i++ ) { $outhash{key1} = $i; push( @array_out, \%outhash ); my %inhash; $inhash{key1} = $i; push( @array_in, \%inhash ); } print "array_out:\n"; foreach my $hashref ( @array_out ) { print "$hashref\n"; } print "array_in:\n"; foreach my $hashref ( @array_in ) { print "$hashref\n"; } output: array_out: HASH(0x183285c) HASH(0x183285c) HASH(0x183285c) HASH(0x183285c) HASH(0x183285c) array_in: HASH(0x198c014) HASH(0x1835164) HASH(0x18351dc) HASH(0x1835254) HASH(0x18352cc)
|
|---|