Perl subroutines are indeed pass-by-reference, meaning that the elements of @_ in your sub are exactly the same elements as were passed to it by the caller. If you manipulate the contents of the elements of @_, you change them in the caller. However, if you assign the elements of @_ to another variable before changing them, you only change the new copy of those data. If you want to change the contents of a hash by calling a subroutine, you can do this:
%a = qw(cat dog);
print $a{cat};
foo(%a);
print $a{cat};
sub foo { $_[1] = "elephant" }
which prints "dog" first, then "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:
%a = qw(cat dog);
print $a{cat};
%a = foo(%a); # <-- note assignment
print $a{cat};
sub foo {
my %temphash = @_;
$temphash{cat} = "elephant";
%temphash;
}
which, while longer, makes it clearer to someone maintaining your code that the
foo subroutine is used to modify the contents of the hash.
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}.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.