正如其他人所提到的,食谱使用术语“适当的”来指代创建一个带有来自更高词法范围的变量的子例程的事实,并且该变量不再可以通过任何其他方式访问。我使用过度简化的助记符“对$color
变量的访问是'关闭'”来记住这部分闭包。
声明“不能为词法变量定义类型团”误解了关于类型团的几个关键点。您将其读作“您不能使用 'my' 来创建 typeglob”,这在某种程度上是正确的。考虑以下:
my *red = sub { 'this is red' };
这将在“my *red”附近出现“语法错误”,因为它试图使用“my”关键字定义类型团。
但是,您示例中的代码并没有尝试这样做。它定义了一个全局的类型团,除非被覆盖。它使用词法变量的值来定义类型团的名称。
顺便说一句,typeglob 可以是词法本地的。考虑以下:
my $color = 'red';
# create sub with the name "main::$color". Specifically "main:red"
*$color = sub { $color };
# preserve the sub we just created by storing a hard reference to it.
my $global_sub = \&$color;
{
# create a lexically local sub with the name "main::$color".
# this overrides "main::red" until this block ends
local *$color = sub { "local $color" };
# use our local version via a symbolic reference.
# perl uses the value of the variable to find a
# subroutine by name ("red") and executes it
print &$color(), "\n";
# use the global version in this scope via hard reference.
# perl executes the value of the variable which is a CODE
# reference.
print &$global_sub(), "\n";
# at the end of this block "main::red" goes back to being what
# it was before we overrode it.
}
# use the global version by symbolic reference
print &$color(), "\n";
这是合法的,输出将是
local red
red
red
在警告下,这将抱怨“Subroutine main::red redefined”