foreach Loops

A foreach loop iterates over an array in order. Every element of the array is placed in a control variable, which then can be used in the following statement block.

Note: the control variable is a reference to the array element; every change made to the control variable will be made in the array as well.

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


@array = (1, 2, 3, 4, 5);

print "Array before loop = @array \n";

foreach $item (@array)  # $item is the control variable
{
  print "$item ";
  ++$item;              # increment each value;
}                       # $item is not a new variable,
                        # but a reference to an array
                        # value; hence, incrementing
                        # $item changes the value in 
                        # the array

print "\nArray after loop = @array \n"; # show new values