我正在尝试从文件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,
},
];
依旧......
然后在包B中,我想以某种方式得到该错误文件。我的想法就是这样:
sub getErrorMap {
my ($self) = @_;
my $map = A::ERROR_ID_MAP;
# Iterate through the array / hash and get the error's default message etc.
}
但这似乎不起作用。另一种选择是将包A变成一个类并且可能返回常量? (在包A中):
sub new {
my ($class, $args) = @_;
my $self;
bless($self, $class);
return $self;
}
sub getErrorConstants {
my $self = @_;
return ERROR_ID_MAP;
}
是否有一种更简单的方法可能只是为了获取ERROR_ID_MAP中的所有数据而不会遇到这种麻烦,所以我们几乎将包A视为各种配置文件?
注意 - 希望上面的代码中没有太多错误会从问题的角度带走。
答案 0 :(得分:6)
虽然@Borodin's answer可能看起来像你想做的那样,但请注意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;
$ ./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,
},
];
!/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;
--- - 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
引用的数据结构元素会导致一个有用的异常。
答案 1 :(得分:2)
您应该编写一个使用Exporter
的模块,比如Definitions.pm
,就像这样
<强> Definitions.pm 强>
package Definitions;
use strict;
use warnings;
use base 'Exporter';
our @EXPORT_OK = qw/ ERROR_ID_MAP /;
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,
},
];
然后您可以use Definitions
并指定要在主代码中导入的常量,例如
<强> main.pl 强>
use strict;
use warnings;
use Definitions qw/ ERROR_ID_MAP /;
use Data::Dump;
dd 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,
},
]
答案 2 :(得分:0)
要使其正常工作,您需要输入
use A;
B.pm
中的