How can I loop through the 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 this?

+6
source share
5 answers
use constant NUCLEOTIDES => [ qw{ A C G T } ];

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

Although be careful: although NUCLEOTIDES is a constant, the elements of the reference array (for example NUCLEOTIDES->[0]) can be changed.

+17
source

Why don't you return the standing list?

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

print for NUCLEOTIDES;

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

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

print for NUCLEOTIDES;

print NUCLEOTIDES->[2];

if you also often need to refer to individual items.

+8
source

,

#!/usr/bin/perl

use strict;
use warnings;

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

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

(=>) .

+3
my $nucleotides = NUCLEOTIDES;

foreach ( @$nucleotides ) { 
}

:

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

:

for my $n ( in NUCLEOTIDES ) { 
}
+1

(This is for completeness, while fooobar.com/questions/1100325 / ... is more elegant)

After unsuccessful attempts, such as @{NUCLEOTIDES}and @{(NUCLEOTIDES)}, I suggested introducing an unused variable my:

foreach (@{my $r = NUCLEOTIDES}) {
}
+1
source

All Articles