David W.
David W.

Reputation: 107060

Perl: Declaring a list of values as a constant

I've been using the [constant] pragma, and have a quick question on how I can declare a constant list:

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

The problem with the last one is that it creates a reference to a list:

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

This works, but it's on the ugly side.

Is there a better way of creating a constant list?

I realize that constants are really just a cheap way of creating a subroutine which returns the value of the constant. But, subroutines can also return a list too.

What is the best way to declare a constant list?

Upvotes: 3

Views: 5630

Answers (3)

Elbin
Elbin

Reputation: 532

If you want a constant array, I'd recommend using Const::Fast, which lets you declare constant scalars, hashes, and arrays.

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

Neil

Upvotes: 0

mob
mob

Reputation: 118635

The constant pragma is just syntactic sugar for a compile-time subroutine declaration. You can do more or less the same thing with a subroutine that returns a list with something like:

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

And then you may say

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

Upvotes: 1

CanSpice
CanSpice

Reputation: 35818

According to the documentation, if you do:

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

...you can then do:

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

I'd say that's nicer than the two ways of referencing constant lists that you have described.

Upvotes: 5

Related Questions