Perl:将值列表声明为常量

时间:2011-10-18 22:40:46

标签: perl

我一直在使用[常量]编译指示,并快速询问如何声明常量列表:

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");
}

这是有效的,但这是丑陋的一面。

是否有更好创建常量列表的方法?

我意识到常量实际上只是一种创建子程序的便宜方式,它返回常量的值。但是,子程序也可以返回一个列表。

声明常量列表的最佳方法是什么?

3 个答案:

答案 0 :(得分:5)

根据the documentation,如果你这样做:

use constant DAYS => qw( Sunday Monday Tuesday Wednesday Thursday Friday Saturday);

......你可以这样做:

my @workdays = (DAYS)[1..5];

我认为这比引用你所描述的常量列表的两种方式更好。

答案 1 :(得分:1)

constant pragma只是编译时子程序声明的语法糖。您可以使用返回列表的子例程执行或多或少相同的操作,例如:

BEGIN {
    *LIST_ONE = sub () { qw(this that the other) }
}

然后你可以说

@list = LIST_ONE;
$element = (LIST_ONE)[1];

答案 2 :(得分:0)

如果你想要一个常量数组,我建议使用Const::Fast,它允许你声明常量标量,散列和数组。

我已经审核了CPAN上用于声明常量的所有不同模块:http://neilb.org/reviews/constants.html

尼尔

相关问题