How can loop through perl constant
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.
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.
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.