in reply to foreach to for (related to my last question)

Why?

By the way, your first snippet simplifies to

sub get_all_seqs{ my $protein = shift; #print "protein = $protein\n"; my @aas = split(//, $protein); my %Deg_codons = get_degenerate(); my @codons = @{$Deg_codons{$aas[0]}}; my %SEQ = map { $_ => 1 } @codons; foreach my $aa (@aas[1..$#aas]) { foreach my $seq (keys %SEQ) { foreach my $codon (@codons) { $SEQ{$seq.$codon} = 1; } delete $SEQ{$seq}; } } return sort keys %SEQ; }

Replies are listed 'Best First'.
Re^2: foreach to for (related to my last question)
by tricolaire (Novice) on Jun 22, 2006 at 00:49 UTC
    so the first version works, the second doesn't

    the second version, when everything to do with $s++ and $s-- is removed, doesn't iterate enough times.

    when the lines with $s are inserted, it goes through to many times and acts upon the wrong data sets. basically I'm asking: how do I replace the foreach loops with for loops?

      basically I'm asking: how do I replace the foreach loops with for loops?

      And I asked why you want to do that. It's like asking how to remove weeds with kitchen utensils when you have perfectly good gardening tools. They're kinda similar, but they have different purposes.

      You have list over which you want to iterate. That's what "foreach" loops do. Counting ("for") loops, on the other hand, cannot iterate over lists. It's possible to store the list in an array, and loop over the indexes of the array, but why do you want to do that?

      To go from a "foreach" loop to a "for" loop, change

      foreach my $item (...list...) { ... }

      to

      my @list = (...list...); for my $i (0..$#list) { my $item = $list[$i]; ... }
      tricolaire:

      Just to amplify on the point ikegami makes: foreach takes care of the niggling little details for you:

    • 0-based or 1-based array? (I code in several languages, so it doesn't stay burned in.)
    • Is my condition == or >=?
    • How do I handle the case if my code adding an item to the list inside the code?
    • Having a nice iterator handle the simple details is a blessing. Why not use it?

      --roboticus

        because I'm trying to change the language in which the algorithm is written. in c++ I don't have the use of the foreach loop, at least, the for_each loop I do have doesn't allow me to change the list.

        so I can't figure out how to deal with the stuff I add or remove, so any help would be nice