Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the benefit of shifting @_ for argument passing in Perl?

sub foo {
 $arg1 = shift @_;
 $arg2 = shift @_;
 # ...
}

What's the benefit of this idiom? I see only disadvantages compared to explicitly working with $_[0], $_[1], ... The array has to be shifted, which is time consuming. It is destroyed, so that at a later point in time, the arguments have vanished (sad if you need them again and have overwritten your $arg1 with a different value).

like image 761
ubuplex Avatar asked Jan 30 '14 09:01

ubuplex


People also ask

What is the use of shift @_ in Perl subroutine?

shift() function in Perl returns the first value in an array, removing it and shifting the elements of the array list to the left by one. Shift operation removes the value like pop but is taken from the start of the array instead of the end as in pop.

What is the difference between shift and @_ used in passing arguments to subroutine?

There is a functional difference ... shift modifies @_ while assignment does not.

What does shift argv do?

If used in the main program, it will shift (remove and return) the first value from @ARGV , the argument list of your program. If used inside a subroutine, it will shift the first value from @_ , the argument list of the sub.

What does @_ mean in Perl?

@ is used for an array. In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function: sub Average{ # Get total number of arguments passed. $ n = scalar(@_); $sum = 0; foreach $item (@_){ # foreach is like for loop...


1 Answers

Shifting @_ is common in OO perl so parameters can be separated from instance of the class which is automatically added as first element of @_.

It can also be used to write less when assigning default values for input parameters, although personally I don't find it appealing,

sub foo {
  my $arg1 = shift // 2;
  my $arg2 = shift // 7;
  # ...
}

I see only disadvantages compared to explicitly working with $[0], $1, ...

Instead of working with $_[0], $_[1], assigning whole @_ array at once is better/less error prone/more readable practice.

my ($arg1, $arg2) = @_;

Also note that @_ elements are aliased to passed variables, so accidental changes could happen,

sub foo {
  $_[0] = 33;
  $_[1] = 44;
}

my ($x, $y) = (11,22);

print "($x, $y)\n";
foo($x, $y);
print "($x, $y)\n";

output

(11, 22)
(33, 44)
like image 191
mpapec Avatar answered Nov 15 '22 08:11

mpapec