When you pass an argument to a function, @_ is an alias to these arguments.

So the following works:

use strict; my $x = 1; modify_args($x), print $x, "\n"; sub modify_args { $_[0] = "modified"; } __END__ modified
But as soon as you assign the values to a new variable, you create a copy:
my $x = 1; modify_args($x), # doesn't work print $x, $/; sub modify_args { my ($copy) = @_; $copy = "modified"; } __END__ 1

Which means that you can change any arguments passed to a sub as long as you stick to manipulating them in @_.

You can circumvent this restriction by passing references , using a module like Data::Bind or Data::Alias), or by creating a new hash and returning that.

If you don't like the last solution (returning a new hash) you should stick to the first one, because of the principle of least surprise: When you call a sub like this: sub_name %hash you don't expect %hash to be modified.

Another possible options are prototypes (notable (\%)), but they come with many problems, and you shouldn't use them until you understood all of these problems


In reply to Re: Modify a hash via its reference by moritz
in thread Modify a hash via its reference by Philippe

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.