English 中文(简体)
Perl: 宣布一个价值清单,作为不变的
原标题:Perl: Declaring a list of values as a constant
  • 时间:2011-10-18 22:40:46
  •  标签:
  • perl

我早就使用了[不变的] p,并且对我如何宣布一个不变的清单存在迅速的问题:

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

这一工作,但进展不大。

是否存在一个固定名单的途径?

我认识到,常数实际上只是一种廉价的方式,可以产生一种回报不变值的支线。 但是,分组也可以返回名单。

什么是宣布经常名单的最佳方式?

最佳回答

http://perldoc.perl.org/constant.html“rel=“noreferer”>。

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

......可以:

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

我要说的是,你所描述的经常名单的两条提及方式不一样。

问题回答

缩略语 你们可以做的是,在一份清单中,有以下几点:

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

那么,你可以说:

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

如果你想要一个固定的阵列,我建议使用Const:Fast,请你宣布固定的ars、 has和阵列。

I ve reviewed all the different modules on CPAN for declaring constants: http://neilb.org/reviews/constants.html.

Neil





相关问题
Why does my chdir to a filehandle not work in Perl?

When I try a "chdir" with a filehandle as argument, "chdir" returns 0 and a pwd returns still the same directory. Should that be so? I tried this, because in the documentation to chdir I found: "...

How do I use GetOptions to get the default argument?

I ve read the doc for GetOptions but I can t seem to find what I need... (maybe I am blind) What I want to do is to parse command line like this myperlscript.pl -mode [sth] [inputfile] I can use ...

Object-Oriented Perl constructor syntax and named parameters

I m a little confused about what is going on in Perl constructors. I found these two examples perldoc perlbot. package Foo; #In Perl, the constructor is just a subroutine called new. sub new { #I ...

Where can I find object-oriented Perl tutorials? [closed]

A Google search yields a number of results - but which ones are the best? The Perl site appears to contain two - perlboot and perltoot. I m reading these now, but what else is out there? Note: I ve ...

热门标签