for Loops

for loops iterate over an array in order. It uses a control variable, an integer, that is used as an index to the array.

In order to execute, a for loop needs three pieces of data: the starting index of the array, the ending index of the array, and the amount by which the index gets incremented or decremented with each iteration. These items are specified after the reserved word for in parentheses, separated by semicolons. The code block within curly braces is executed with every iteration.

Copy the text below and run it as a Perl script.


@array = ("George", "Harry", "Ezio", "Helmut", "Waltraud");

# iterate over the array in ascending order:
# the first element of an array is indexed as 0; 
# in Perl @array evaluated in a scalar context returns 
# of the array
for ($i = 0; $i < @array; ++$i) # = (start_index; end_index; increment)
{
  print $i;
  print " $array[$i]\n"; # print the($i+1)th element 
}

print "\n\n";

# iterate over the array in descending order
for ($i = @array - 1; $i >= 0; --$i)
{
  print $i;
  print " $array[$i]\n"; # print the($i+1)th element 
}

print "\n\n";

# iterate over the array in ascending order,
# skipping all even-numbered elements
for ($i = 1; $i < @array; $i = $i + 2)
{
  print $i;
  print " $array[$i]\n"; # print the($i+1)th element 
}