sna*_*pan 2 perl config constants
我正在尝试从文件A.pm中定义的Perl文件中提取一些常量
package A;
use constant ERROR_ID_MAP => [
PLAYBACK_ERROR => {
defaultMessage => "Sorry there was an error with a playback",
errorCode => 0,
},
PURCHASE_ERROR => {
defaultMessage => "Sorry, we've encountered a problem with purchasing. Please try again.",
errorCode => 2123,
},
];
Run Code Online (Sandbox Code Playgroud)
等等...
然后在包B中,我想以某种方式得到该错误文件.我的想法就是这样:
sub getErrorMap {
my ($self) = @_;
my $map = A::ERROR_ID_MAP;
# Iterate through the array / hash and get the error's default message etc.
}
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用.另一种选择是将包A变成一个类并且可能返回常量?(在包A中):
sub new {
my ($class, $args) = @_;
my $self;
bless($self, $class);
return $self;
}
sub getErrorConstants {
my $self = @_;
return ERROR_ID_MAP;
}
Run Code Online (Sandbox Code Playgroud)
是否有一种更简单的方法可能只是为了获取ERROR_ID_MAP中的所有数据而不经历这个麻烦,所以我们几乎将包A视为各种配置文件?
注意 - 希望上面的代码中没有太多的错误会从问题的角度带走.
虽然@ Borodin的答案可能看起来像是在做你想要的,但要注意constant.pm下面的例子演示了一些细微差别:
#!/usr/bin/env perl
use strict;
use warnings;
use YAML::XS;
use constant X => [ { test => 1 }];
print Dump X;
X->[0]{test} = 3;
print Dump X;
Run Code Online (Sandbox Code Playgroud)
$ ./zxc.pl --- - test: 1 --- - test: 3
use constant X => [ ... ]表示常量子程序始终返回相同的引用.但是,您可以操纵该引用指向的元素.如果您确实想要导出常量,请考虑使用Const :: Fast:
package Definitions;
use strict;
use warnings;
use Const::Fast;
use Exporter qw( import );
our @EXPORT = qw();
our @EXPORT_OK = qw( $ERROR_ID_MAP );
const our $ERROR_ID_MAP => [
PLAYBACK_ERROR => {
defaultMessage => "Sorry there was an error with a playback",
errorCode => 0,
},
PURCHASE_ERROR => {
defaultMessage => "Sorry, we've encountered a problem with purchasing. Please try again.",
errorCode => 2123,
},
];
Run Code Online (Sandbox Code Playgroud)
!/usr/bin/env perl
use strict;
use warnings;
use YAML::XS;
use Definitions qw( $ERROR_ID_MAP );
print Dump $ERROR_ID_MAP;
$ERROR_ID_MAP->[1]{errorCode} = 3;
Run Code Online (Sandbox Code Playgroud)
--- - PLAYBACK_ERROR - defaultMessage: Sorry there was an error with a playback errorCode: 0 - PURCHASE_ERROR - defaultMessage: Sorry, we've encountered a problem with purchasing. Please try again. errorCode: 2123 Modification of a read-only value attempted at ./main.pl line 11.
请注意如何尝试更改$ERROR_ID_MAP引用的数据结构的元素会导致有用的异常.