in reply to Passing hashes by reference
which prints "dog" first, then "elephant".%a = qw(cat dog); print $a{cat}; foo(%a); print $a{cat}; sub foo { $_[1] = "elephant" }
However, such code is Bad because there's nasty magical action-at-a-distance. In fact, if I saw code like that I would assume it was a bug. You're better off doing this:
which, while longer, makes it clearer to someone maintaining your code that the foo subroutine is used to modify the contents of the hash.%a = qw(cat dog); print $a{cat}; %a = foo(%a); # <-- note assignment print $a{cat}; sub foo { my %temphash = @_; $temphash{cat} = "elephant"; %temphash; }
Another way would be to explicitly pass the subroutine a reference to the hash and then use the -> operator to modify what the reference refers to. When doing that, it is still common to copy the reference to the hash into a scalar in your subroutine, but when you do that, you can still dereference it and $reference->{wibble} is far easier to read than $_[0]->{wibble}.
|
|---|