Understanding the unexpected result you're getting will really help you in the future.

use strict; my (%hash,@array); $hash{A}='B'; push @array,\%hash;

I have pushed into my array a hash reference. If I run this in the debugger, I can see the following:

x @array 0 HASH(0x300331c4) 'A' => 'B'

Resuming:

$hash{B}='C'; push @array, \%hash;

But:

x @array 0 HASH(0x300331c4) 'A' => 'C' 1 HASH(0x300331c4) -> REUSED_ADDRESS

I thought I pushed a different value into the array. I expect two hashes in my array, one with value B and one with C. But that's not what I get. A reference is not a copy of the variable, but a link to that variable. My array contains two references to the same variable, %hash. The first array element reflects the new value in %hash, 'C', and the second just says 'ditto'.

use strict; my (%hash,@array); $hash{A}='B'; push @array, \%hash; my (%hash); $hash{A}='C'; push @array, \%hash;

Debugger shows:

x @array 0 HASH(0x30033194) 'A' => 'B' 1 HASH(0x3015f4e0) 'A' => 'C'

This time, I created a new hash variable, so the array contains two distinct references. The first array element is unchanged by my actions.

In this example, it appears I have lost that first %hash by reusing the name. In fact, I can no longer retrieve its values using that name. But the value is preserved by the reference in the array.

Minor update made for clarity.

But God demonstrates His own love toward us, in that while we were yet sinners, Christ died for us. Romans 5:8 (NASB)


In reply to Re^3: Assign a hash to an array by GotToBTru
in thread Assign a hash to an array by ravi45722

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.