I have been following the tutorials on perlmeme.org and some of the authors declare variables in following way:
my $num_disks = shift || 9; # - no idea what
shift
is a function that takes an array, removes the first element of it and returns that element. If the array is empty, it returns undef
. If shift gets no arguments, then it automatically works on the @_
array when inside subroutine (otherwise it uses @ARGV
).
Arguments to functions are placed in the array @_
.
So if we write a function that takes two arguments, we can use shift twice to put them into variables:
sub add {
my $a = shift;
my $b = shift;
return $a + $b;
}
And now add(3,4) would return 7.
The notation
my $a = shift || 1;
is simply a logical or. This says that if the result of shift
is falsy (undef, zero, or empty string for instance) then use the value 1. So that's a common way of giving defaults to function arguments.
my $a = shift // 1;
is similar to previous example but it assigns default value only when shift()
returns undef
.