【问题标题】:What is the value if you shift beyond the last element of an array?如果超出数组的最后一个元素,值是多少?
【发布时间】:2013-06-01 16:39:47
【问题描述】:

在这段代码中,使用了两次 shift,尽管该方法只接受一个参数:

sub regexVerify ($)
{
   my $re = shift;

   return sub
   {
      local $_ = shift;
      m/$re/ ? $_ : undef;
   };
}

一旦再次使用 shift,这会使本地 $_ 的值变成什么?我(也许天真地)假设转变为虚无会导致undef。但如果是这样的话,这句话就没有意义了,对吧?:

m/$re/ ? $_ : undef;

上面的子调用如下:

regexVerify (qr/^([a-z].*)?$/i);

【问题讨论】:

  • 标题问题的答案是:undef

标签: arrays perl null shift undef


【解决方案1】:

第二个shift 在内部sub 声明中。该作用域将有一个全新的@_ 可以使用,这与传递给外部子例程的@_ 没有任何关系。

regexVerify 是一个返回另一个子程序的子程序。大概您稍后会使用参数调用该子例程:

my $func = regexVerify(qr/^([a-z].*)?$/i);
# $func is now a "code reference" or "anonymous subroutine"

...

if ($func->($foo)) {    # invoke the subroutine stored in $func with arg ($foo)
    print "$foo is verified.\n";
} else {
    print "$foo is not verified!\n";
}

【讨论】:

  • 有道理,但我还是不明白 --- 如果内部 sub 不带参数,如果不是 undef,本地 $_ 被初始化为什么?
  • @CptSupermrkt 内部子 does 带参数,重新阅读 mob 的答案。 regexVerify 返回一个 sub,然后像 $func->($This_Is_A_Parameter) 一样调用它!
  • 它确实需要一个参数,在示例中为$foo
【解决方案2】:

local $_ = shift; 在您调用匿名函数之前不会被执行。即

my $anon_func = regexVerify (qr/^([a-z].*)?$/i);

# NOW sending arguments in @_ for local $_ = shift;
print $anon_func->("some string"); 

【讨论】:

    猜你喜欢
    • 2017-08-11
    • 2017-02-27
    • 1970-01-01
    • 2019-04-08
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 2012-02-18
    相关资源
    最近更新 更多