Developer Forums | About Us | Site Map
Search  
HOME > TUTORIALS > SERVER SIDE CODING > PERL TUTORIALS > ROAD TO BETTER PROGRAMMING: CHAPTER 3. LOOPS, CLEAN CODE, AND THE PERL IDIOMS


Sponsors





Useful Lists

Web Host
site hosted by netplex

Online Manuals

Road to better programming: Chapter 3. Loops, clean code, and the Perl idioms
By Teodor Zlatanov - 2004-02-16 Page:  1 2 3 4 5

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



foreach (1..100)
{
 # do something 100 times, $_ will be set to the current number
 print "Now on iteration $_\n";
}
foreach (1..20,101..120)
{
 # do something 40 times, $_ will be set to the current number
}
foreach my $counter (0..1)
{
 # do something twice, $counter will be 0, then 1
}
foreach my $i (0..1000)
{
 next unless $i%5;                      # next if this number is a multiple of 5
 print "$i is not a multiple of 5...\n";
 next unless $i%7;                      # next if this number is a multiple of 7
 print "$i is not a multiple of 7...\n";
 next unless $i%12;                     # next is this number is a multiple of 12
 # $i is now not a multiple of 12, 5, or 7
 print "$i is a lucky, lucky number to have met you...\n";
}
# here we use the Perl map operator to create a list of 100 even numbers
# see chapter 5 for details on the map and grep operators
foreach (map { $_ *= 2 } 0..99)
{
 print "Even number: $_\n";


View Road to better programming: Chapter 3. Loops, clean code, and the Perl idioms Discussion

Page:  1 2 3 4 5 Next Page: If, else, elsif, unless, or, how to confuse a cat

First published by IBM developerWorks


Copyright 2004-2024 GrindingGears.com. All rights reserved.
Article copyright and all rights retained by the author.