使用 perl 的 do 时的执行规则。

Execution rules when using perl's do.

我有一个关于 perl 如何执行 "do" 函数的问题。

假设我有一个函数是这样的:

sub foo {
    package bar;
    %bar::h_test = ('b' => 'blah');
}

当使用严格和警告时,这 运行 就好了。 现在假设我有以下 perl 脚本,"test.pl":

%h_test = ('b' => 'blah');

现在我可以重写之前的函数如下:

sub foo {
    package bar;
    do ('test.pl');
}

似乎 "do" 允许我使用非限定名称,只要我将它们保存在文件中即可。我理解为什么从设计的角度来看这是有意义的,因为那里的每个脚本都不可能知道调用它的人。但是,我不确定 运行ning 代码的确切规则是什么 "do" 允许它。

那么,它是如何工作的?阅读 perldoc 并没有对这个主题有太多的了解

谢谢。

test.pl 中没有用 our 声明 %h_test 时没有出现编译时错误的原因是你在 use strict您的主脚本没有扩展到文件 test.pl。根据 the documentation:

The strict pragma disables certain Perl expressions that could behave unexpectedly or are difficult to debug, turning them into errors. The effect of this pragma is limited to the current file or scope block.

还要注意 the documentation for do 说:

do './stat.pl' is largely like:

eval `cat stat.pl`;

except that it's more concise, runs no external processes, and keeps track of the current filename for error messages. It also differs in that code evaluated with do FILE cannot see lexicals in the enclosing scope

此外,根据 the documentation use strict 'vars' 如果名称是完全限定的,则不会生成错误。所以这就解释了为什么在使用 strict 时可以写 %bar::h_test = ('b' => 'blah') 而无需使用 our.

声明变量