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