in reply to Re^3: How come @_ gets changed here?
in thread How come @_ gets changed here?

So what's the take-away here? If your sub has to put stuff in variables outside its own scope, don't also pass those variables as parameters?

Replies are listed 'Best First'.
Re^5: How come @_ gets changed here?
by dave_the_m (Monsignor) on Jun 10, 2017 at 19:04 UTC
    the rough rule is: don't free elements of arrays and hashes (e.g. by assigning a list to the array or hash) when those elements are currently the arguments of a funtion call, or are being iterated over by for(), etc.

    Dave.

      Please correct me if I'm wrong, but as long as I copy the args in my first line, it should be safe from messed up ref counts, shouldn't it?

      my ($a, $b) = @_

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!

Re^5: How come @_ gets changed here?
by LanX (Saint) on Jun 10, 2017 at 19:08 UTC
    > So what's the take-away here? If your sub has to put stuff in variables outside its own scope, don't also pass those variables as parameters?

    It's even more complicated.

    You could call another sub (which calls another sub) which is deleting elements from the closure before accessing @_.

    I think the rule of thumb is

    • always try to copy @_ first and avoid accessing any $_[n] afterwards.
    • if you really need the aliasing effect or high performance, be sure to avoid side effects by calling unknown functions or even directly overwriting closed over vars.

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!