ViceRaid has asked for the wisdom of the Perl Monks concerning the following question:
Patient ones:
Perl surprised me again this morning. I wanted to *copy* an anonymous hash by dereferencing it, and then creating a new reference to it, leaving me with two references to two different hashes. So I did:
my $this = { 'name' => 'alex' }; my $that = \%{ $this }; # now i thought that $that would be an independent copy, but: $that->{'name'} = 'madonna'; print $this->{'name'}; # oh no! i'm madonna! they both referenced the same thing
This surprised me, because I thought dereferencing would make it just a 'free-floating' anonymous hash. This works fine, but is an extra line:
my $this = { 'name' => 'alex' }; my %that = %{ $this }; my $that = \%that; # now $that really is an independent copy, and: $that->{'name'} = 'madonna'; print $this->{'name'}; #alex # phew! I'm still me!
My questions are: 1) why does this happen like this? I don't really see what the difference is between the first and the second code sample. What subtlety am I missing? 2) Is there a neater way of writing the second sample, which does what I want, without using the throwaway named hash %that?
with thanks
/=\
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: hash dereferencing / copying
by broquaint (Abbot) on Feb 27, 2002 at 12:59 UTC | |
|
Re: hash dereferencing / copying
by strat (Canon) on Feb 27, 2002 at 13:25 UTC | |
by PrakashK (Pilgrim) on Feb 27, 2002 at 15:34 UTC | |
by IlyaM (Parson) on Feb 27, 2002 at 23:18 UTC | |
|
Re: hash dereferencing / copying
by Ido (Hermit) on Feb 27, 2002 at 13:36 UTC |