我一直在使用 [constant] pragma,有一个关于如何声明常量列表的快速问题:
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
};
最后一个问题是它创建了对列表的引用:
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");
}
这行得通,但它有丑陋的一面。
是否有更好的方法来创建常量列表?
我意识到常量实际上只是一种创建返回常量值的子例程的廉价方法。但是,子程序也可以返回一个列表。
声明常量列表的最佳方式是什么?
最佳答案
根据 the documentation ,如果你这样做:
use constant DAYS => qw( Sunday Monday Tuesday Wednesday Thursday Friday Saturday);
...然后你可以这样做:
my @workdays = (DAYS)[1..5];
我会说这比您描述的两种引用常量列表的方法更好。
关于Perl:将值列表声明为常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7814642/