What could the following line possibly mean?
my $x = shift;
What could the following line possibly mean?
my $x = shift;
shift()
is a built in Perl subroutine that takes an array as an argument, then returns and deletes the first item in that array. It is common practice to obtain all parameters passed into a subroutine with shift
calls. For example, say you have a subroutine foo
that takes three arguments. One way to get these parameters assigned to local variables is with shift
like so:
sub foo() {
my $x = shift;
my $y = shift;
my $z = shift;
# do something
}
The confusion here is that it appears shift is not being passed an array as an argument. In fact, it is being passed the "default" array implicitly, which is @_
inside a subroutine or @ARGV
outside a subroutine.
The shift
function removes the first element from an array, and returns it. The array is shortened by one element.
The default array (if one isn't given as a parameter) is @_
if you're in a function, or @ARGV
if you're at file scope.
So in this case $x
is either being set to the first function parameter, or to the first command line parameter.
In Perl, many methods use the default variables ($_
and @_
) if you don't explicitly specify arguments. Your code is identical to:
my $x = shift @_;
As pointed out by PullMonkey earlier, within a subroutine, @_
contains the arguments passed to that subroutine (as described in perlsub
). shift
will remove the first argument value from @_
and store it in $x
, so $_[0]
will now give you the second argument passed to your subroutine.
This is usually an idiom for: $x is a local variable assigned to the first parameter passed to the subroutine, although.
my ($x) = @_;
is probably clearer (and it doesn't modify the argument list).
in a layman's language,from a very highlevel view, shift is taking the first element of an array (the leftmost part), while the opposite is pop which is taking the last element of array (the rightmost part).
my @array1=(5,6,7,8,9); my $x = shift @array1; print "$x\n"; # 5 print "@array1\n"; # 6 7 8 9
If you are in a subroutine this line will shift
on @_
(the params that are passed in).
So $x
would be the first item popped
from the @_
array.
So usually you would see $x = shift if @_;