in reply to shift vs @_
# 1. non-destructive my $var = $_[0]; # first element of @_ my @list = @_; # complete @_ # 2. destructive my $var = shift; # first element gets removed + from @_ my ($foo, $bar) = map { shift } 1,2; # two elements get removed f +rom @_
If @_ needs to be intact for subsequent calls, as in
sub foo { my $foo = $_[0]; my $quux = baz(@_) return $foo ^= $quux; }
the non-destructive methods are used. Also, as the variables passed in via the vector @_ are references aliases to the thingies the caller provided, the non-destructive way is often used to do in-place transformations.
Otherwise, it just doesn't matter. Since after setting up the variables in the sub's scope @_ isn't looked at anymore, arguments may be shifted or not. In these cases saying $var = shift or $var = $_[0] does the same for the sub, although the impact on @_ is different.
So, saying $var = shift and @list = @_ is just caring about copying, but done that, not caring about @_ any more.
Using the arguments in a sub without prior assignment (i.e. without copying, as $_[0] .. $_[$#_]) modifies the thingies in the caller.
--shmem
<update> changed reference to alias as per tye's post </update>
_($_=" "x(1<<5)."?\n".q·/)Oo. G°\ / /\_¯/(q / ---------------------------- \__(m.====·.(_("always off the crowd"))."· ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: shift vs @_
by BerntB (Deacon) on Oct 03, 2006 at 09:21 UTC | |
by shmem (Chancellor) on Oct 03, 2006 at 20:50 UTC | |
by tye (Sage) on Oct 03, 2006 at 21:26 UTC |