Think lists and iterators. The length may not ever be evaluated in Perl - it's more complicated than that, and you don't need to know. :)
Take a trawl through the STL and you will find equivelent constructs to foreach: for_each in <algorithm> for example.
Update: just to make it a little clearer - Perl generates the list for the foreach "up front" before the first iteration of the loop. If your loop is over an array, the list is the array. If the loop is over something like keys of a hash or lines of a file a temporary list is generated.
DWIM is Perl's answer to Gödel
| [reply] |
for (1 .. 2_000_000_000) {
print "$_\n";
}
You will see by checking memory consumption that the list is not generated.
| [reply] [d/l] |
Unfortunately, the story is about as clear as mud.
Agreed. The important point for OP is that it is not clear when or if Perl ever calculates the number of items. In many cases Perl simply doesn't know or care. For OP's purposes when, how or if Perl ever evaluates the number of items is actually irrelevant, but OP hasn't figured that out yet. C++ is a whole different world, but the STL does provide similarly anonymous management of lists.
DWIM is Perl's answer to Gödel
| [reply] |
Word of advice, pick "for" or "foreach" and use one. Minor nit, but they're interchangable, and switching back and forth tends to make it less readable for me.
And just a quick note:
for( my $i=1; $i<@aas; $i++){
#etc
}
can be written more perlish as (assuming you really want elements 0 .. $#aas of @aas, instead of 1..$#aas+1):
for( @aas ){
@codons = @{$Deg_codons{$_}};
for my $seq( keys %SEQ ){
for my $codon( @codons ){
$SEQ{$seq.$codon}=1;
}
delete $SEQ{$seq};
}
}
There are probably some other changes that could be made here, but these are just the ones that jump off the page at me.
--chargrill
$,=42;for(34,0,-3,9,-11,11,-17,7,-5){$*.=pack'c'=>$,+=$_}for(reverse s
+plit//=>$*
){$%++?$ %%2?push@C,$_,$":push@c,$_,$":(push@C,$_,$")&&push@c,$"}$C[$#
+C]=$/;($#C
>$#c)?($ c=\@C)&&($ C=\@c):($ c=\@c)&&($C=\@C);$%=$|;for(@$c){print$_^
+$$C[$%++]}
| [reply] [d/l] [select] |
| [reply] [d/l] [select] |
And, for yet another way to do it, I follow the same pattern of for for indexing and foreach for aliasing, but I build indexing loops as
for my $i (0..$#arr) {
do_whatever();
}
instead of doing it C-style (unless I need a more complex index transition than the usual $i++). | [reply] [d/l] [select] |
As shown bellow, the first for loop
produces fixed iterations, and the second
dives into infinite loop. Although expectations are
not consistent, at least you get to chose which method
to want.
## Fixed-length Loop
my $i=6;
for (0..$i) {
print ;
$i++;
}
#### Infinite Loop
my @nums = 1..3;
for (@nums) {
push @nums, $_;
print;
}
| [reply] [d/l] |