sub foo { # pass by ref my $ref = shift; $ref->{one} = q{One}; $ref = {}; # why won't this replace the underlying hash? return $ref; }
I think your confusion comes from thinking you are doing a pass by reference like commented with # pass by ref
But your code $ref = shift; is literally a pass by value , $ref will be the copy of a (Perl) reference.
For a pass-by-reference you have to replace $ref with $_[0] , which is an "alias" of the original argument $foo.
Hence will $_[0] = {}; also replace the original hash.
I know it's confusing but "reference" in CS lingo is NOT a reference in Perl lingo, but best translated as "alias".
Cheers Rolf
(addicted to the Perl Programming Language :)
Wikisyntax for the Monastery
In reply to Re: unexpected behavior on hash passed by reference
by LanX
in thread unexpected behavior on hash passed by reference
by perlfan
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |