in reply to Trouble with hashrefs
$hash = thaw builds a new structure and replaces the reference in $hash with a reference to that structure. It does not change $href or what it points to.
The following illustrates memory contents after each statement:
sub do_stuff { +-----+ +------------------+ $href --->| a: --->| status: "OK" | +-----+ +------------------+ my $hash = shift; +-----+ +------------------+ $href --->| a: --->| status: "OK" | $hash / +-----+ +------------------+ my $hash2 = freeze($hash); +-----+ +------------------+ $href --->| a: --->| status: "OK" | $hash / +-----+ +------------------+ +--------------------------------+ $hash2 = | Frozen image of | | +-----+ +------------------+ | | | a: --->| status: "OK" | | | +-----+ +------------------+ | +--------------------------------+ $hash->{'a'}->{'status'} = "NOT OK"; +-----+ +------------------+ $href --->| a: --->| status: "NOT OK" | $hash / +-----+ +------------------+ +--------------------------------+ $hash2 = | Frozen image of | | +-----+ +------------------+ | | | a: --->| status: "OK" | | | +-----+ +------------------+ | +--------------------------------+ $hash = thaw($hash2); +-----+ +------------------+ $href --->| a: --->| status: "NOT OK" | +-----+ +------------------+ +--------------------------------+ $hash2 = | Frozen image of | | +-----+ +------------------+ | | | a: --->| status: "OK" | | | +-----+ +------------------+ | +--------------------------------+ +-----+ +------------------+ $hash --->| a: --->| status: "OK" | +-----+ +------------------+ print "IN SUB: " . $hash->{'a'}->{'status'} . "\n"; return 0; }
The simplest and safest solution is to not change the structure in the first place by working on a copy of it.
sub do_stuff { my $hash = dclone(shift); $hash->{'a'}->{'status'} = "NOT OK"; print "IN SUB: " . $hash->{'a'}->{'status'} . "\n"; }
sub do_stuff { +-----+ +------------------+ $href --->| a: --->| status: "OK" | +-----+ +------------------+ my $hash = dclone(shift); +-----+ +------------------+ $href --->| a: --->| status: "OK" | +-----+ +------------------+ +-----+ +------------------+ $hash --->| a: --->| status: "OK" | +-----+ +------------------+ $hash->{'a'}->{'status'} = "NOT OK"; +-----+ +------------------+ $href --->| a: --->| status: "OK" | +-----+ +------------------+ +-----+ +------------------+ $hash --->| a: --->| status: "NOT OK" | +-----+ +------------------+ print "IN SUB: " . $hash->{'a'}->{'status'} . "\n"; return 0; }
|
|---|