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)
|