It would make a lot of things easier in my script if I could use subroutines in the way that shift, push, and other built-in subroutines work: they can all directly change the variable that is passed to it without the need to return the change.
When I try to do this the variable is copied at some point and I appear to be simply changing the copy. I understand that this would be fine with references but it even happens with arrays and hashes, where I feel like I am simply passing the variable I was working on to the sub so that more work can be done on it:
@it = (10,11);
changeThis(@it);
print join(" ", @it),"\n"; #prints 10 11 but not 12
sub changeThis{
$_[2] = 12;
}
Is there a way to do this? I understand that it isn’t best practice, but in my case it would be very convenient.
The problem is that the sub call expands the variable to a list of values, which are passed on to the sub routine. I.e. a copy is passed, not the variable itself. Your sub call is equal to:
If you wish to change the original array, pass a reference instead:
Also,
@_[2]will give you the warning:If you
use warnings, which of course you should. There is no good reason to not turn on warnings and strict, unless you know exactly what you are doing.