如何在Perl中的不同包之间共享全局值?

Ben*_*oît 6 perl global-variables

是否有一种标准方法来编写模块以保存全局应用程序参数以包含在每个其他包中?例如:use Config;

一个只包含our变量的简单包?那些只读变量怎么样?

Gre*_*con 8

已经有一个标准的Config模块,因此请选择其他名称.

假设您拥有MyConfig.pm以下内容:

package MyConfig;

our $Foo = "bar";

our %Baz = (quux => "potrzebie");

1;
Run Code Online (Sandbox Code Playgroud)

然后其他模块可能会使用它

#! /usr/bin/perl

use warnings;
use strict;

use MyConfig;

print "Foo = $MyConfig::Foo\n";

print $MyConfig::Baz{quux}, "\n";
Run Code Online (Sandbox Code Playgroud)

如果您不想完全限定名称,请使用标准的Exporter模块.

添加三行MyConfig.pm:

package MyConfig;

require Exporter;
our @ISA = qw/ Exporter /;
our @EXPORT = qw/ $Foo %Baz /;

our $Foo = "bar";

our %Baz = (quux => "potrzebie");

1;
Run Code Online (Sandbox Code Playgroud)

现在不再需要完整的包名称:

#! /usr/bin/perl

use warnings;
use strict;

use MyConfig;

print "Foo = $Foo\n";

print $Baz{quux}, "\n";
Run Code Online (Sandbox Code Playgroud)

你可以只读标量增加MyConfig.pm

our $READONLY;
*READONLY = \42;
Run Code Online (Sandbox Code Playgroud)

这在perlmod中有记录.

添加后@MyConfig::EXPORT,您可以尝试

$READONLY = 3;
Run Code Online (Sandbox Code Playgroud)

在一个不同的模块中,但你会得到

Modification of a read-only value attempted at ./program line 12.

作为替代方法,您可以MyConfig.pm使用常量模块声明常量,然后导出它们.

  • 您可以只使用`import`方法,而不是继承自`Exporter`,这是您真正需要的.例如`使用Exporter'import';` (2认同)