Array

The foreach construct

The foreach construct iterates over a list of scalar values (i.e. that are contained in an array) and executes a block of code for each of the values.

Example:

foreach $i (@some_array) {
   statement_1;
   statement_2;
   statement_3;
}

Each element in @some_array is aliased to the variable $i in turn, and the block of code inside the curly brackets {} is executed once for each element.

The variable $i (or give it any other name you wish) is local to the foreach loop and regains its former value upon exiting of the loop.

Examples for using the foreach construct

Subtraction of a constant number from each array element:

#!/usr/bin/perl

@measurement = (3, 2, 5, 9, 7, 13, 16);

foreach $i (@measurement) {
   $i = $i - 2;
}

#Now @measurement contains (1, 0, 3, 7, 5, 11, 14)

Printing the array elements, each in a separate line:

#!/usr/bin/perl

@measurement = (3, 2, 5, 9, 7, 13, 16);

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

Now try a combination of both:

#!/usr/bin/perl

@measurement = (3, 2, 5, 9, 7, 13, 16);

foreach $k (@measurement) {
   print "$k becomes ";
   $k = $k - 2;
   print "$k\n";
}
Output:
3 becomes 1
2 becomes 0
5 becomes 3
9 becomes 7
7 becomes 5
13 becomes 11
16 becomes 14

Table of Contents.
Previous | Next.