3.1.13 Looping Through Every Element of a List or an Array

There are several ways we can loop through every element of a array. We have already seen how we can use the for loop along with a numeric index that steps from 0 to the last index in the array. We will see another way to iterate over every element of an array.

We can use the foreach construct to loop through every element of a loop. The foreach construct has the structure

foreach $variable (@list){...}

$variable is the loop control variable. It is bound to an individual element of the array at a time. To start, $variable is bound to the first element of the list or the array; the body of the loop is performed for this bound value. Then, the variable is bound to the second element of the array and the body of the loop is executed for this value. This way it continues till the whole list is traversed.

Once again, the following program prints every element of an array in HTML format.

Program 3.7

#!/usr/bin/perl
#file friends9.pl

use strict;

my (@friends, $friend);
@friends =  ('Michael Saden', 'Brent Hays', 'John Hart', 'Jeff Ellis', 
             'Brett Walters', 'Blake Escort', 'Tom Toybee');

print "
    \n"; foreach $friend (@friends){ print "
  • $friend
  • \n"; } print "
\n";

If the loop control variable is not specified, it is implicitly taken to be the special variable $_. We have another version of the preceding program below.

Program 3.8

#!/usr/bin/perl
#file friends10.pl

use strict vars;

my @friends;
@friends =  ('Michael Saden', 'Brent Hays', 'John Hart', 'Jeff Ellis', 
             'Brett Walters', 'Blake Escort', 'Tom Toybee');

print "
    \n"; foreach (@friends){ print "
  • $_
  • \n"; } print "
\n";

The only difference between this program and the previous one is in the string argument to print inside the foreach loop. The use of $_ makes the second program a bit tighter, but cryptic at the same time.