OfficialBenWhite
OfficialBenWhite

Reputation: 141

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

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 the shift does

and within loops like

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

when you use

print Dumper ( $source ); 

the result is undef

Why can you not just use

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

to declare the variables?

Upvotes: 3

Views: 227

Answers (1)

RemcoGerlich
RemcoGerlich

Reputation: 31270

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.

Upvotes: 11

Related Questions