aztlan667 has asked for the wisdom of the Perl Monks concerning the following question:
OK, I've been beating my head against a very BASIC hashref problem. I'm trying to save the state of a hashref before and after a subroutine which might make assignments to the hashref. I've tried using Storable to either dclone or freeze/thaw the structure, but the subroutine continues to give me weird results. Here's an example:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; use Storable qw(dclone freeze thaw); my $href = undef; $href = { 'a' => { 'status' => 'OK' }}; print "BEFORE SUB: " . $href->{a}->{status} . "\n"; do_stuff($href); print "AFTER SUB: " . $href->{a}->{status} . "\n"; sub do_stuff { my $hash = shift; my $hash2 = freeze($hash); $hash->{'a'}->{'status'} = "NOT OK"; $hash = thaw($hash2); print "IN SUB: " . $hash->{'a'}->{'status'} . "\n"; return 0; }
This code returns the following:
$ ~/test.pl BEFORE SUB: OK IN SUB: OK AFTER SUB: NOT OK
Am I missing something completely obvious? The value of $hash->{'a'}->{'status'} is getting overwritten to "NOT OK" in the sub, but then the entire hashref gets reassigned at the end of the sub, and the status is once again "OK". Once I'm out of the sub, the value returned is still "NOT OK". I don't get it. I'm completely familiar with the concepts of pass-by-reference (at least I thought I was). But if I'm completely reassigning the reference, shouldn't that be what the final value of the hashref is? I'm assuming the nested references also get overwritten, but I'm not sure. Any advice along the lines of "Hey, stupid, don't you know that...." would be greatly appreciated.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Trouble with hashrefs
by ikegami (Patriarch) on Mar 17, 2010 at 23:13 UTC | |
|
Re: Trouble with hashrefs
by almut (Canon) on Mar 17, 2010 at 22:57 UTC |