I am looping through the contents of a file and generating a hash inside that loop for each matched string I find. After I make the hash, I push a reference to that hash onto an array.

After I push all 400+ hash references onto my array, it appears that somehow all of the references in the array point to the very last hash that was pushed onto the array. I can't figure out why this is happening.

I can run the debugger and watch my array of hash references populate exactly like I want, and I can step all the way through the looping code to the end of the loop and my array of hash references (and all the data those references point to in the hash) look correct.

Then as soon as I leave the block looping code, each hash reference in my array points to the hash that was pushed onto the array last.

Why is this happening? Any help is greatly appreciated. I have included a snippet of my code below:

=================================
### $html contains contents of a file while($html =~ <some regex here>){ $player{'gp'}=$1; $player{'min'}=$2; $player{'fgm'}=$3; $player{'fga'}=$4; $player{'fgp'}=$5; $player{'tpm'}=$6; $player{'tpa'}=$7; $player{'tpp'}=$8; push (@players, \%player); $html=$'; } ###Once I get here, every hash ref in the array points to ###the same +hash (the last one to be pushed onto the array. ###Each of the follo +wing lines then prints out ###the same data. print "Size of \@players: ".$#players." Element 0 is: $players[0]{ +'min'} "."\n"; print "Size of \@players: ".$#players." Element 1 is: $players[1]{ +'min'} "."\n"; print "Size of \@players: ".$#players." Element 2 is: $players\[2\ +]{'min'} "."\n";
=================================

Again, thank you in advance for any help that is provided.

In reply to 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.