在我正在处理的脚本中,我有类似于以下内容的内容:
require "environment.pm"; # Various definitions, including subroutine get_coll()
use Custom::Module;
在
Custom::Module
文件,我从package Custom::Module;
并以
1;
当我尝试调用
get_coll()
时我收到一个错误:( main::get_coll() ) being undefined.
如果我需要
Custom::Module
而不是使用或更改调用Custom::Module::get_coll();
它工作正常。这让我相信
CustomModule
的“使用”声明正在更改“事件”命名空间,因此当 get_coll()
被处理(因为它是在调用时处理的)它被分配给那个命名空间而不是主命名空间。这似乎不是常规 perl 模块的问题,但是从我查看的模块来看,我没有注意到任何不同的东西会导致命名空间在模块加载后“恢复”到 main。任何有助于更好地理解命名空间使用或修复模块以不导致此问题的帮助将不胜感激。旁注:对我来说,仅仅“要求”模块并不是什么大问题,但这对我来说是意外的行为,所以我主要只是想更好地了解发生了什么。
最佳答案
我试图完全按照您的描述重新创建文件。这是我的三个源文件
你说
In a script I am working on, I have something similar to the following:
require "environment.pm"; # Various definitions, including subroutine get_coll() use Custom::Module;
和
When I try to call get_coll() I get an error about it
虽然你没有说你在哪里调用
get_coll
,但我想它在主脚本中,我认为这相当于这个脚本文件my_script.pl
use strict;
use warnings;
use 5.010;
require 'environment.pm';
use Custom::Module;
say get_coll();
和这个模块文件
环境.pm
use strict;
use warnings;
use 5.010;
sub get_coll {
return 'coll';
}
1;
然后你说
In the
Custom::Module
file, I start withpackage Custom::Module;
and end with
1;
所以我写了这个模块文件。它没有任何内容,因为您没有描述任何内容
自定义/模块.pm
use strict;
use warnings;
use 5.010;
package Custom::Module;
1;
现在,当我运行
my_script.pl
时,我得到coll
没有警告或错误消息,这完全符合我的预期
我担心你说
environment.pm
包含 get_coll
,但你可以调用 Custom::Module::get_coll
。 Custom/Module.pm
是否也有 require 'environment.pm'
? 如果您能指出我误解您描述的地方,请指出,因为我目前无法复制您的问题,因此无法为您提供帮助
否则,我建议您使用这三个文件来创建问题的 Short, Self-Contained, Correct Example。这将极大地帮助我们为您找到解决方案
关于perl - 在使用自定义模块后分配给错误命名空间的所需文件中定义的子例程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30403766/