我一直在使用[常量]编译指示,并快速询问如何声明常量列表:
use constant {
LIST_ONE => qw(this that the other), #BAD
LIST_TWO => ("that", "this", "these", "some of them"), #BAR
LIST_THREE => ["these", "those", "and thems"], #WORKS
};
Run Code Online (Sandbox Code Playgroud)
最后一个问题是它创建了对列表的引用:
use constant {
LIST_THREE => ["these", "those", "and thems"],
};
# Way 1: A bit wordy and confusing
my $arrayRef = LIST_THREE;
my @array = @{$arrayRef};
foreach my $item (@array) {
say qq(Item = "$item");
}
# Way 2: Just plain ugly
foreach my $item (@{&LIST_THREE}) {
say qq(Item = "$item");
}
Run Code Online (Sandbox Code Playgroud)
这是有效的,但它在丑陋的一面.
有没有更好的方法来创建常量列表?
我意识到常量实际上只是创建子例程的一种廉价方法,它返回常量的值.但是,子程序也可以返回一个列表.
声明常量列表的最佳方法是什么?
根据文档,如果您这样做:
use constant DAYS => qw( Sunday Monday Tuesday Wednesday Thursday Friday Saturday);
Run Code Online (Sandbox Code Playgroud)
......你可以这样做:
my @workdays = (DAYS)[1..5];
Run Code Online (Sandbox Code Playgroud)
我会说这比引用你所描述的常量列表的两种方式更好.