When a subroutine is called, the passed parameters are put into a special array @_
. One can consume this array by shifting values out my $foo = shift
or by direct array assignment my ($foo,$bar)=@_;
It is even possible to use the values directly from the array: $_[0]
Why one versus the others? Direct array assignment is the most standard and common. Sometimes the shift way is used when there are optional trailing values. Direct array usage is discouraged except in few small niches: wrapper functions that are calling other functions, especially inside of objects. functions that wrap other functions and and modify the inputs. Also the special form of goto &func
which immediately drops the current call stack and calls func on the current value of @_
.
# use shift for optional trailing values
use v5.10;
my $foo = shift;
my $bar = shift // 'default bar value';
my $baz = shift // 'default baz value';
#obj method to call related non-object function.
sub bar { my $self = shift; _bar(@_) }
sub longname { shortname(@_) }
sub get { return $_[0]->$_[1]; }