导出变量很容易导致麻烦。
Why not
package XYZ;
use strict;
use warnings;
use Exporter qw(import);
our @EXPORT_OK = qw(get_var);
my $VAR = '...'; # no need for "our" now
sub get_var { return $VAR }
...
1;
and then
package THIS;
use warnings;
use strict;
use XYZ qw(get_var);
my $var = get_var();
...
1;
See Exporter http://perldoc.perl.org/Exporter.html.
至于你试图做什么,有两个直接问题
-
$VAR
from XYZ
is never imported into THIS
. If you need symbols from other packages you need to import them.† Those packages have to make them available first, so you need to add it to @EXPORT_OK
as well.
Like above but with $VAR
instead of get_var()
package XYZ;
...
use Exporter qw(import);
our @EXPORT_OK = qw($VAR);
our $VAR = '...'; # need be "our" for this
with
package THIS;
...
use XYZ qw($VAR);
print "$VAR\n";
Now $VAR
可以直接使用,包括正在写信给(除非声明为常量);它可以在其他代码的脚下改变它的值,而其他代码甚至可能永远不知道其中的任何一个。
另一种方法是使用@EXPORT
然后这些符号被引入到每个程序中use Package;
。我强烈建议只使用@EXPORT_OK
,当呼叫者需要明确列出他们想要的内容时。这也很好地记录了正在使用的内容。
-
即使添加了该内容,仍然存在一个同名变量THIS
,隐藏(遮罩、阴影)$XYZ::VAR
。所以删除our $VAR
in THIS
。这是全局变量问题的一个很好的例子。一旦它们被引入我们就必须小心它们always and 到处.
但跨模块共享变量存在更大的问题。
它使代码组件变得纠缠在一起,并且代码变得越来越难使用。它违背了明确定义的范围和模块化设计的原则,它支持远距离操作等。Perl 提供了许多用于构建代码的好工具,我们很少需要全局变量和共享变量。它告诉我们的是Exporter
itself 警告不要这样做 http://perldoc.perl.org/Exporter.html#What-Not-to-Export.
Note how now my $VAR
in XYZ
is not visible outside XYZ
; there is no way for any code outside XYZ
to know about it or to access it.‡ When it is our
then any code in the interpreter can write it simply as $XYZ::VAR
, and without even importing it; that's what we don't want.
当然,可能需要或很好地使用导出变量,这些变量偶尔可以在模块中找到。但这是一个例外,请谨慎使用。
† Unless they're declared as package globals under a lexical alias via our https://perldoc.perl.org/functions/our in their package https://perldoc.perl.org/functions/package, in which case they can be used anywhere as $TheirPackageName::varname
.
‡ This complete privacy is courtesy of my https://perldoc.perl.org/perlsub#Private-Variables-via-my%28%29.