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).
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.
There is a functional difference ... shift modifies @_ while assignment does not.
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.
@ 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...
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With