Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 552
Jessada Thutkawkorapin Avatar asked Jan 23 '12 13:01

Jessada Thutkawkorapin


4 Answers

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.

like image 101
zgpmax Avatar answered Nov 06 '22 22:11

zgpmax


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.

like image 8
Eric Strom Avatar answered Nov 06 '22 23:11

Eric Strom


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.

like image 3
Chas. Owens Avatar answered Nov 06 '22 23:11

Chas. Owens


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 ) { 
}
like image 1
Axeman Avatar answered Nov 06 '22 23:11

Axeman