gpt4 book ai didi

Perl 闭包和 $_

转载 作者:行者123 更新时间:2023-12-03 01:29:20 26 4
gpt4 key购买 nike

我尝试学习一种不熟悉的编程语言的第一件事就是它如何处理闭包。它们的语义通常与语言处理范围和其他各种棘手位的方式交织在一起,因此理解它们可以揭示该语言的其他几个方面。另外,闭包是一种非常强大的构造,并且通常会减少我必须输入的样板文件的数量。所以我在摆弄 Perl 闭包时偶然发现了一个小问题:

my @closures;
foreach (1..3) {
# create some closures
push @closures, sub { say "I will remember $_"; };
}
foreach (@closures) {
# call the closures to see what they remember
# the result is not obvious
&{$_}();
}

当我编写上面的代码时,我期待看到

I will remember 1
I will remember 2
I will remember 3

但我得到了我会记住代码(0x986c1f0)

上述实验表明,$_ 非常依赖于上下文,如果它出现在闭包中,那么它的值在闭包创建时并不是固定的。它的行为更像是一个引用。在 Perl 中创建闭包时我还应该注意哪些其他问题?

最佳答案

闭包仅关闭词法变量; $_ 通常是全局变量。在 5.10 及更高版本中,您可以说 my $_; 使其在给定范围内成为词法(尽管在 5.18 中这被追溯声明为实验性的并且可能会发生变化,因此最好使用其他一些变量名)。

这会产生您期望的输出:

use strict;
use warnings;
use 5.010;
my @closures;
foreach my $_ (1..3) {
# create some closures
push @closures, sub { say "I will remember $_"; };
}
foreach (@closures) {
# call the closures to see what they remember
# the result is not obvious
&{$_}();
}

关于Perl 闭包和 $_,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4665268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com