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:

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)
@array_out is filled with refs to the same hash, but each ref in @array_in is unique.


In reply to Re: Array of Hashes question by bobf
in thread Array of Hashes question by no21

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.