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 ?
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.
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 ) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With