为什么裸块无法访问范围变量和函数如果打包?

rog*_*ger 1 perl

我想is在裸体块中定义一个类并进行测试,如下所示:

use Test::More tests => 1;

{
    package Foofle;
    use parent qw(Animal);
    sub sound { 'foof' }

    is(
        Foofle->speak,
        "A Foofle goes foof!\n",
        "An Animal subclass does the right thing"
    );
}
Run Code Online (Sandbox Code Playgroud)

我收到了错误Undefined subroutine &Foofle::is called at t/Animal.t,所以如果我补充一下

use Test::More;
Run Code Online (Sandbox Code Playgroud)

在裸体块中,它运行正常.

或者我走出is裸露的街区,

use Test::More tests => 1;

{
    package Foofle;
    use parent qw(Animal);
    sub sound { 'foof' }
}

is(
    Foofle->speak,
    "A Foofle goes foof!\n",
    "An Animal subclass does the right thing"
);
Run Code Online (Sandbox Code Playgroud)

它运行正常.但为什么裸块无法访问范围变量?

sfe*_*cik 5

您的use Test::More呼叫将标识符is导入当前包.在您的第一个实现中,这意味着导入is到脚本的包中,这可能是main包.之后,每次ismain包中使用时,Perl都知道它应该调用Test::More::is.

现在,只要切换到另一个包,就is不再是同义词Test::More::is.事实上,你可以尝试这样做:is()在你的裸体块中调用,但你声明之前package Foofle.它应该工作得很好.不应该责怪赤裸裸的街区; 事实上,你现在处于一个不同的包装中.

正如您已经尝试过的那样,use Test::More在您的Foofle包装中也有一个选择.另一种是使用原始实现,但is使用完全限定名称调用:Test::More::is(Foofle->speak, "...", "...");.