What does shift() do in Perl?

cam picture cam · Nov 17, 2008 · Viewed 46.3k times · Source

What could the following line possibly mean?

my $x = shift;

Answer

cowgod picture cowgod · Nov 17, 2008

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.