For and foreach: how to have fun and get away with it
Because of the (ahem) rich cultural heritage of the for() loop, I recommend that foreach() be used instead. This is for several reasons:
- foreach() sounds better in English.
- foreach() is an explicit break from the C tradition, whereas for() may confuse novice programmers.
- There's no difference between the two at the interpreter level.
If you feel you must use the for() loop, I suggest that you heavily document its occurrences and your reasoning for its use. While for() has its uses, especially in the three-argument form, it is a tool best avoided by novice and intermediate programmers.
The improvement mentioned above is that the foreach() loop takes an argument that is a list. That's very useful, because lists are a basic data type in Perl, and many wonderful things can be done with them. For instance, the list of 2 through 40 is written as "2..40" in Perl. For every element of the list, the body of the foreach() loop is executed once. As with the while() and do-until() loops, the "next" and "last" keywords can change the program flow through the loop. "Next" and "last" skip to the next element and exit the loop altogether, respectively. Here are some examples:Listing 4. The foreach() loop