在Perl中,如何访问另一个包中定义的标量? [英] In Perl, how can I access a scalar defined in another package?
问题描述
我似乎在尝试访问在另一个程序包中定义的标量时陷入困境,并且将示例缩小为一个简单的测试用例,可以在其中重现问题. 我希望能够使用我们的机制访问包"Example"中定义的列表的引用,但是,Dumper显示出example.pl中始终未定义变量:
I seem to be stuck trying to access a scalar which is defined in another package, and have narrowed down an example to a simple test case where I can reproduce the issue. What I wish to be able to do it access a reference to a list which is in defined within the package 'Example', using the our mechanism, however, Dumper is showing that the variable is always undefined within example.pl:
Example.pm如下所示:
Example.pm looks like the following:
#!/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;
使用此软件包的代码如下:
And the code which uses this package looks like this:
#!/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;
运行此代码后,第一个Dumper运行并且看起来一切正常,此后,第二个Dumper example.pl运行,然后未定义引用:
Upon running this code, the first Dumper runs and things look normal, after this, the second Dumper, example.pl runs and the reference is then undefined:
$VAR1 = [
'one',
'two',
'three'
];
$VAR1 = undef;
推荐答案
即使$exported_array
不在Example
包,Example
的$exported_array
和 main的 $exported_array
是两件事.更改示例的最简单方法是将1.在Example
声明中将my
更改为our
并明确限定变量名.
Even if $exported_array
weren't lexically scoped in the Example
package, Example
's $exported_array
and main's $exported_array
are two different things. The easiest way to change the example you've given is to 1. change my
to our
in the Example
declaration and explicitly qualify the variable name.
our $exported_array;
...
print Dumper $Example::exported_array;
否则,您需要将Example
设置为 Exporter
一个>. (或者只是编写一个Example::import
例程-但我不打算介绍它.)
Otherwise, you need to make Example
an Exporter
. (Or just write an Example::import
routine--but I' not going to cover that.)
package Example;
our $exported_array = ...;
our @EXPORT_OK = qw<$exported_array>;
use parent qw<Exporter>;
在脚本中:
use Example qw<$exported_array>;
但是,由于您实际上可以导出 arrays (不仅仅是引用),所以我会做到这一点:
However, as you can actually export arrays (not just refs), I would make that:
our @exported_array = (...);
our @EXPORT_OK = qw<@exported_array>;
...
use Example qw<@exported_array>;
...
print Dumper( \@exported_array );
这篇关于在Perl中,如何访问另一个包中定义的标量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!