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

后端 未结 1 1433
青春惊慌失措
青春惊慌失措 2021-01-20 09:42

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          


        
1条回答
  •  醉梦人生
    2021-01-20 10:04

    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.

    0 讨论(0)
提交回复
热议问题