in reply to Re: Dynamically changing the value of a passed variable into a sub (see node below, this one got submitted in error)
in thread Dynamically changing the value of a passed variable into a sub
However, his assertion that arguments are passed by value is not quite correct. In fact, arguments are passed "by alias", which is essentially under-the-hood references.
When the docs say that the sub receives the argument list in @_, what they really mean is that each element of @_ is an alias to the actual argument.
This means that modifying an element of @_ modifies the actual argument.
So -- as a possible alternative -- instead of doing
you can in fact do this:modify( \$val ); sub modify { my $ref = shift; $$ref ++; # or whatever }
However, just because you can do this, doesn't mean you should. This technique is considered by many to be Bad Programming.modify( $val ); sub modify { $_[0] ++; # or whatever. }
The other issue to be aware of -- for future reference -- is that constant values can not be modified*. If you try, perl will barf.
*This is always true**, but having the modification down in a subroutine can make you forget.
**That is, constant values can't be modified within Perl code. By calling low-level (C) code, e.g. via XS, anything is possible.
|
|---|