从Perl模块导出所有常量(只读变量)的最有效方法是什么

CRO*_*OSP 8 perl constants perl-module perl-exporter

我正在寻找从我的单独模块中导出所有常量的最有效和可读的方法,该模块仅用于存储常量.
例如

use strict;
use warnings;

use Readonly;

Readonly our $MY_CONSTANT1         => 'constant1';
Readonly our $MY_CONSTANT2    => 'constant2'; 
....
Readonly our $MY_CONSTANT20    => 'constant20';
Run Code Online (Sandbox Code Playgroud)

所以我有很多变量,并将它们全部列在我们的内部@EXPORT = qw( MY_CONSTANT1.... );
它会很痛苦.是否有任何优雅的方式导出所有常量,在我的情况下,Readonly变量(强制导出所有,不使用@EXPORT_OK).

ike*_*ami 5

实际常数:

use constant qw( );
use Exporter qw( import );    

our @EXPORT_OK;

my %constants = (
   MY_CONSTANT1 => 'constant1',
   MY_CONSTANT2 => 'constant2',
   ...
);

push @EXPORT_OK, keys(%constants);
constant->import(\%constants);
Run Code Online (Sandbox Code Playgroud)

使用 Readonly 将变量设为只读:

use Exporter qw( import );
use Readonly qw( Readonly );

our @EXPORT_OK;

my %constants = (
   MY_CONSTANT1 => 'constant1',
   MY_CONSTANT2 => 'constant2',
   #...
);

for my $name (keys(%constants)) {
   push @EXPORT_OK, '$'.$name;
   no strict 'refs';
   no warnings 'once';
   Readonly($$name, $constants{$name});
}
Run Code Online (Sandbox Code Playgroud)


Sin*_*nür 5

如果这些是可能需要插入字符串等的常量,请考虑将相关常量分组到散列中,并使用Const :: Fast使散列变为常量.这减少了命名空间污染,允许您检查特定组中的所有常量等.例如,考虑IE的属性的READYSTATE枚举值ReadyState.您可以将它们分组为哈希,而不是为每个值创建单独的变量或单独的常量函数:

package My::Enum;

use strict;
use warnings;

use Exporter qw( import );
our @EXPORT_OK = qw( %READYSTATE );

use Const::Fast;

const our %READYSTATE => (
    UNINITIALIZED => 0,
    LOADING => 1,
    LOADED => 2,
    INTERACTIVE => 3,
    COMPLETE => 4,
);

__PACKAGE__;
__END__
Run Code Online (Sandbox Code Playgroud)

然后,您可以直观地使用它们,如:

use strict;
use warnings;

use My::Enum qw( %READYSTATE );

for my $state (sort { $READYSTATE{$a} <=> $READYSTATE{$b} } keys %READYSTATE) {
    print "READYSTATE_$state is $READYSTATE{$state}\n";
}
Run Code Online (Sandbox Code Playgroud)

另见Neil Bowers对'用于定义常数的CPAN模块'的出色评论.