是否有一种标准方法来编写模块以保存全局应用程序参数以包含在每个其他包中?例如:使用Config;?
一个只包含我们变量的简单包?那些只读变量怎么样?
解决方法
已经有一个
standard Config module,所以选择一个不同的名称.
假设您有MyConfig.pm,其中包含以下内容:
- package MyConfig;
- our $Foo = "bar";
- our %Baz = (quux => "potrzebie");
- 1;
然后其他模块可能会使用它
- #! /usr/bin/perl
- use warnings;
- use strict;
- use MyConfig;
- print "Foo = $MyConfig::Foo\n";
- print $MyConfig::Baz{quux},"\n";
在MyConfig.pm中添加三行:
- package MyConfig;
- require Exporter;
- our @ISA = qw/ Exporter /;
- our @EXPORT = qw/ $Foo %Baz /;
- our $Foo = "bar";
- our %Baz = (quux => "potrzebie");
- 1;
现在不再需要完整的包名称:
- #! /usr/bin/perl
- use warnings;
- use strict;
- use MyConfig;
- print "Foo = $Foo\n";
- print $Baz{quux},"\n";
你可以用MyConfig.pm添加一个只读标量
- our $READONLY;
- *READONLY = \42;
这在perlmod中记录.
将它添加到@MyConfig :: EXPORT后,您可以尝试
- $READONLY = 3;
在一个不同的模块中,但你会得到
- Modification of a read-only value attempted at ./program line 12.
作为替代方案,您可以使用constant模块在MyConfig.pm常量中声明,然后导出它们.