sub reduce(&@) {

    my $expr = \&{shift @ARG};

    my $result = shift @ARG;
    while (scalar @ARG > 0) {
        our $a = $result;
        our $b = shift @ARG;
        $result = $expr->();
    }

    return $result;
}

我无法真正理解这段代码中的某些语法。谁能给我解释一下?像 \&$result = $expr->()

最佳答案

\&name 返回对名为 name 的子例程的引用。
$code_ref->() 调用 $code_ref 引用的子程序。

$ perl -e'
    sub f { CORE::say "Hi" }
    my $code_ref = \&f;
    $code_ref->();
'
Hi

在你的情况下,shift @ARG 返回一个子程序引用,所以
my $expr = \&{shift @ARG};

可以写成
my $expr = shift @ARG;

这有点像做 $y = $x+1-1;

请注意, reduce 的原型(prototype)允许将其称为
reduce { ... } ...

但实际执行的是
reduce(sub { ... }, ...)

请注意,这个版本的 reduce 有问题。您应该使用 List::Util 提供的那个。
  • local $alocal $b 应该用于避免破坏其调用者可能在 $a$b 中拥有的值。
  • 此版本的 reduce 期望其回调与 reduce 本身在同一包中编译。否则,回调子将无法简单地使用 $a$b
  • 在这个版本的情况下,使用 our 声明变量实际上是完全没有用的,因为 $a$b 免于 use strict; 检查,并且 $a$b 的未声明使用将访问完全相同的包变量。
  • 关于perl -\& 和 $expr->() 的用法是什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40011866/

    10-14 16:21
    查看更多