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
/=\In reply to hash dereferencing / copying by ViceRaid
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |