为什么我不能通过typeglob访问词法变量?

时间:2013-02-16 13:49:16

标签: perl

我不明白为什么下面的例子失败了(测试2)。为什么我无法从* bb glob访问变量bb?

use Test::More tests => 4;

$aa = 1;
my $bb = 2;   # HERE!
local $cc = 3;
our $dd = 4;

is(${*aa}, 1, "$ \*aa should be 1");
is(${*bb}, 2, "$ \*bb (my) should be 2");
is(${*cc}, 3, "$ \*cc (local) should be 3");
is(${*dd}, 4, "$ \*dd (our) should be 4");

输出

1..4
ok 1 - *aa should be 1
#   Failed test '*bb (my) should be 2'
#   at untitled line 10.
#          got: undef
#     expected: '2'
# Looks like you failed 1 test of 4.
not ok 2 - *bb (my) should be 2
ok 3 - *cc (local) should be 3
ok 4 - *dd (our) should be 4

根据perl 5.16.0

由于

1 个答案:

答案 0 :(得分:7)

词法变量(使用my创建的变量)不是符号表的一部分,因此 globs 无法访问它们。另请参阅Of Symbol Tables and Globs