Why do some programmers declare variables like my $ myvariable = shift; in Perl?

I follow tutorials on perlmeme.org and some authors declare variables like this:

my $num_disks = shift || 9; # - no idea what the shift does

      

and inside loops like

my $source = shift;
my $dest = shift;
my $how_many = shift;

      

when you use

print Dumper ( $source ); 

      

the result is undef

Why can't you just use

my $num_disks = 9;
my $source;
my $dest;
my $how_many;

      

to declare variables?

+3


source to share


1 answer


shift

is a function that takes an array, removes the first element, and returns that element. If the array is empty, it returns undef

. If shift takes no arguments, it automatically works on an array @_

when inside a subroutine (otherwise it uses @ARGV

).

Function arguments are placed in an array @_

.

So, if we write a function that takes two arguments, we can use shift twice to put them in variables:

sub add {
    my $a = shift;
    my $b = shift;
    return $a + $b;
}

      

Now adding (3,4) will return 7.



Designation

my $a = shift || 1;

      

is just logical or. This suggests that if the result shift

is false (for example, undef, zero, or an empty string), then use the value 1. Thus, the general way of providing function arguments is by default.

my $a = shift // 1;

      

is similar to the previous example, but only assigns a default value when it shift()

returns undef

.

+11


source







All Articles