6

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 ?

2
  • 2
    'use constant' is more trouble than it's worth here. Why not just 'our @NUCLEOTIDES = qw(A C G T);' ?? Commented Jan 23, 2012 at 17:56
  • Because the information in this constant is not going to be modified through out the run-time even though it's not really that 'constant' here. Commented Jan 30, 2012 at 13:55

5 Answers 5

17
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.

Sign up to request clarification or add additional context in comments.

Comments

8

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.

1 Comment

You first function is equivalent to use constant NUCLEOTIDES => qw/A C G T/.
3

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.

Comments

1
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 ) { 
}

Comments

1

(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}) {
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.