[ACCEPTED]-What does shift() do in Perl?-built-in

Accepted answer
Score: 65

shift() is a built in Perl subroutine that takes 12 an array as an argument, then returns and 11 deletes the first item in that array. It 10 is common practice to obtain all parameters 9 passed into a subroutine with shift calls. For 8 example, say you have a subroutine foo that 7 takes three arguments. One way to get these 6 parameters assigned to local variables is 5 with shift like so:

sub foo() {
  my $x = shift;
  my $y = shift;
  my $z = shift;
  # do something

The confusion here is that 4 it appears shift is not being passed an 3 array as an argument. In fact, it is being 2 passed the "default" array implicitly, which 1 is @_ inside a subroutine or @ARGV outside a subroutine.

Score: 15

The shift function removes the first element 7 from an array, and returns it. The array 6 is shortened by one element.

The default 5 array (if one isn't given as a parameter) is 4 @_ if you're in a function, or @ARGV if you're 3 at file scope.

So in this case $x is either 2 being set to the first function parameter, or 1 to the first command line parameter.

Score: 10

In Perl, many methods use the default variables 8 ($_ and @_) if you don't explicitly specify 7 arguments. Your code is identical to:

my $x = shift @_;

As 6 pointed out by PullMonkey earlier, within 5 a subroutine, @_ contains the arguments passed 4 to that subroutine (as described in perlsub). shift will 3 remove the first argument value from @_ and 2 store it in $x, so $_[0] will now give you the 1 second argument passed to your subroutine.

Score: 3

This is usually an idiom for: $x is a local 4 variable assigned to the first parameter 3 passed to the subroutine, although.

my ($x) = @_;

is probably 2 clearer (and it doesn't modify the argument 1 list).

Score: 3

In layman's terms, from a very highlevel 4 view, shift is taking the first element of an 3 array (the leftmost part), while the opposite 2 is pop which is taking the last element of 1 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
Score: 1

If you are in a subroutine this line will 3 shift on @_ (the params that are passed in).
So 2 $x would be the first item popped from the @_ array.

So 1 usually you would see $x = shift if @_;

More Related questions