我似乎被困在尝试访问另一个包中定义的标量,并将示例缩小到一个简单的测试用例,我可以重现这个问题.我希望能够使用我们的机制访问对包'Example'中定义的列表的引用,但是,Dumper显示该变量在example.pl中始终未定义:
Example.pm如下所示:
#!/usr/bin/perl -w
use strict;
use warnings;
use diagnostics;
package Example;
use Data::Dumper;
my $exported_array = [ 'one', 'two', 'three' ];
print Dumper $exported_array;
1;
Run Code Online (Sandbox Code Playgroud)
使用此包的代码如下所示:
#!/usr/bin/perl -w
use strict;
use warnings;
use diagnostics;
use Data::Dumper;
use lib '.';
use Example;
{ package Example;
use Data::Dumper;
our $exported_array;
print Dumper $exported_array;
}
exit 0;
Run Code Online (Sandbox Code Playgroud)
在运行此代码时,第一个Dumper运行并且事情看起来正常,此后,第二个Dumper,example.pl运行,然后引用未定义:
$VAR1 = [
'one',
'two',
'three'
];
$VAR1 = undef;
Run Code Online (Sandbox Code Playgroud)
一个my
声明不创建一个包级别的变量和任何命名空间不输入任何东西到符号表.
要做你想要做的事情,你必须将第一个文件中的声明更改为
our $exported_array = [ ... ];
Run Code Online (Sandbox Code Playgroud)
然后,您可以在另一个文件中访问它
$Example::exported_array
Run Code Online (Sandbox Code Playgroud)
即使$exported_array
没有在词法作用域Example
包Example
的$exported_array
和主要的 $exported_array
是两个不同的东西.改变你给的例子,最简单的方式是1的变化my
,以our
在Example
声明中,明确限定的变量名.
our $exported_array;
...
print Dumper $Example::exported_array;
Run Code Online (Sandbox Code Playgroud)
否则,你需要做Example
一个Exporter
.(或者只是写一个Example::import
例行公事 - 但我不打算这样做.)
package Example;
our $exported_array = ...;
our @EXPORT_OK = qw<$exported_array>;
use parent qw<Exporter>;
Run Code Online (Sandbox Code Playgroud)
并在脚本中:
use Example qw<$exported_array>;
Run Code Online (Sandbox Code Playgroud)
但是,因为你可以实际导出数组(不仅仅是引用),我会这样做:
our @exported_array = (...);
our @EXPORT_OK = qw<@exported_array>;
...
use Example qw<@exported_array>;
...
print Dumper( \@exported_array );
Run Code Online (Sandbox Code Playgroud)