tcf03 has asked for the wisdom of the Perl Monks concerning the following question:

Can someone help me to understand the behavior of the following code? Im unable to find this documented.
#!/usr/bin/perl -w use strict; my %animals=( 'cow' => "bessie", 'horse' => "ed", 'duck' => "goose", 'dog' => "rexx" ); print "my animals\n"; print_hash(); my $ranimals=\%animals; $$ranimals{'duck'} = "franklin"; print "\nmy referenced animals\n"; print_hash(); sub print_hash { for ( sort keys(%animals) ) { print "$_ = $animals{$_}\n"; } }
when I change $$ranimals{'duck'} to shouldnt $animals{'duck'} still be "goose"? Or am I just greatly misunderstanding what this is doing?

Update
after typing this out I think Im seeing the error of my ways. Im going to leave the question stand though. My original intention was to review a lot of the code ive written over the years and bring my code more into line with my understanding of perl now. Ive recently read a few books such as "Effective Perl Programming" and "Advanced Perl Programming" and am trying to bring my skills to a higher level. I think I need to have another go-round with perlref.

Ted

Replies are listed 'Best First'.
Re: references changing a hash value
by davorg (Chancellor) on Apr 26, 2005 at 15:21 UTC

    Try changing the line to

    my $ranimals = { %animals };

    to see the behaviour that you expected. In this case, you are creating a _copy_ of the hash and getting a reference to the new copy. In your original code you are taking a reference to the original (and only!) hash so any changes you make through the reference effect the original array.

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: references changing a hash value
by tlm (Prior) on Apr 26, 2005 at 13:53 UTC

    No. When you take a reference to a hash (or anything else) with \ you are not making a copy. Dereferencing the reference accesses the original.

    the lowliest monk

Re: references changing a hash value
by splinky (Hermit) on Apr 26, 2005 at 14:01 UTC
    $ranimals is a reference to %animals, so they both point at the same thing. So, when you change $$ranimals{'duck'}, you're also changing $animals{'duck'}.