next up previous contents
Next: The for statement Up: Control Structures Previous: The while statement   Contents


The foreach loop

The while loop can be used to do most iterative tasks, but some tasks are so common and useful that perl provides additional control statements to make those tasks easier. One such task is repeatedly accessing each element in an array or a list of scalar values; the foreach statement makes looping over a list of values very easy, since you don't have to specify exactly how many elements are in the array, or any particular condition for the loop to terminate.

The basic form of the foreach statement is


  

foreach var (list)
block of statements
The variable var will take on each value stored in list in turn, executing the block of statements and continuing on to the next value in the list. The variable var is local to the foreach loop; if a variable outside the loop has the same name, it is unaffected by the foreach loop. In fact, var is optional; if you don't specify a variable in the foreach statement, the special variable $_ can be used inside the loop to represent the values in list.

Since you don't have to bother with subscripting, the foreach loop is very convenient when you wish to process all of the elements of an array or list. So to print all of the names in an array called @names, we could use the following statements:

     foreach $i (@names){
          print "$i\n";
     }

The example of adding together all the values of an array shown in Section 5.5 could much more simply be done with a foreach loop.

     $total = 0;
     foreach $p (@prices){
          $total += $p;
     }

Even though each element of the array being processed is represented by a variable with a different name than the array, that variable is simply an alias for the value contained in the array. In particular, changes you make to that variable are reflected in the array itself; in fact, using a foreach loop to modify some or all of the elements of an array is one of the most common uses of the construct.

To illustrate this, suppose we had an array called nums consisting of numeric values and we wanted to change all the values which were less than zeroes to zero. We could use a foreach loop as follows:

     @nums = (7,9,-5,3,-2,1);
     foreach $n (@nums){
         $n = 0 if $n < 0;
     }
     print join(' ',@nums);  # prints 7 9 0 3 0 1
Even though we never explicitly refered to the @nums array in the interior of the loop, its values were still modified.


next up previous contents
Next: The for statement Up: Control Structures Previous: The while statement   Contents
Phil Spector 2002-10-18