Jessada Thutkawkorapin
Jessada Thutkawkorapin

Reputation: 1346

How can loop through perl constant

I want to do the same as below

my @nucleotides = ('A', 'C', 'G', 'T');
foreach (@nucleotides) {
    print $_;
}

but using

use constant NUCLEOTIDES => ['A', 'C', 'G', 'T'];

How can I do that ?

Upvotes: 6

Views: 4195

Answers (5)

U. Windl
U. Windl

Reputation: 4325

(This is for completeness, while https://stackoverflow.com/a/8972542/6607497 is more elegant)

After having tried things like @{NUCLEOTIDES} and @{(NUCLEOTIDES)} unsuccessfully, I came up with introducing an unused my variable:

foreach (@{my $r = NUCLEOTIDES}) {
}

Upvotes: 1

Axeman
Axeman

Reputation: 29854

my $nucleotides = NUCLEOTIDES;

foreach ( @$nucleotides ) { 
}

Or you could make this utility function:

sub in (@) { return @_ == 1 && ref( $[0] ) eq 'ARRAY' ? @{ shift() } : @ ; }

And then call it like this:

for my $n ( in NUCLEOTIDES ) { 
}

Upvotes: 1

Chas. Owens
Chas. Owens

Reputation: 64919

If you want to use the constant pragma, then you can just say

#!/usr/bin/perl

use strict;
use warnings;

use constant NUCLEOTIDES => qw/A C G T/;

for my $nucleotide (NUCLEOTIDES) {
   print "$nucleotide\n";
}

The item on the right of the fat comma (=>) does not have to be a scalar value.

Upvotes: 3

Eric Strom
Eric Strom

Reputation: 40152

Why not make your constant return a list?

sub NUCLEOTIDES () {qw(A C G T)}

print for NUCLEOTIDES;

or even a list in list context and an array ref in scalar context:

sub NUCLEOTIDES () {wantarray ? qw(A C G T) : [qw(A C G T)]}

print for NUCLEOTIDES;

print NUCLEOTIDES->[2];

if you also need to frequently access individual elements.

Upvotes: 8

zgpmax
zgpmax

Reputation: 2847

use constant NUCLEOTIDES => [ qw{ A C G T } ];

foreach (@{+NUCLEOTIDES}) {
    print;
}

Though beware: Although NUCLEOTIDES is a constant, the elements of the referenced array (e.g. NUCLEOTIDES->[0]) can still be modified.

Upvotes: 17

Related Questions