为什么有些程序员声明像my myvariable = shift这样的变量; 在Perl?

Off*_*ite 3 perl

我一直在关注perlmeme.org上的教程,一些作者以下列方式声明变量:

my $num_disks = shift || 9; # - no idea what the shift does
Run Code Online (Sandbox Code Playgroud)

并在循环内

my $source = shift;
my $dest = shift;
my $how_many = shift;
Run Code Online (Sandbox Code Playgroud)

当你使用

print Dumper ( $source ); 
Run Code Online (Sandbox Code Playgroud)

结果是undef

为什么你不能只使用

my $num_disks = 9;
my $source;
my $dest;
my $how_many;
Run Code Online (Sandbox Code Playgroud)

声明变量?

Rem*_*ich 11

shift是一个接受数组的函数,删除它的第一个元素并返回该元素.如果数组为空,则返回undef.如果shift没有参数,那么它@_在子程序内部时自动对数组起作用(否则使用@ARGV).

函数的参数放在数组中@_.

因此,如果我们编写一个带有两个参数的函数,我们可以使用shift两次将它们放入变量中:

sub add {
    my $a = shift;
    my $b = shift;
    return $a + $b;
}
Run Code Online (Sandbox Code Playgroud)

现在添加(3,4)将返回7.

符号

my $a = shift || 1;
Run Code Online (Sandbox Code Playgroud)

只是一个逻辑或.这表示如果结果shift是假的(例如undef,zero或空字符串),则使用值1.这是给函数参数提供默认值的常用方法.

my $a = shift // 1;
Run Code Online (Sandbox Code Playgroud)

与前面的示例类似,但它仅在shift()返回时指定默认值undef.

  • 但是不要使用_ $ a_和_ $ b_作为函数参数,它是为[sort](http://perldoc.perl.org/functions/sort.html)函数保留的.:) (3认同)