"Perl for Perl Newbies" - Part 1ArraysThe foreach loop

9.3. The foreach loop

By using the foreach loop we can iterate over all the elements of an array, and perform the same set of operations on each one of them. Here's an example:

@numbers = (15,5,7,3,9,1,20,13,9,8,
	15,16,2,6,12,90);

$max = $numbers[0];
$min = $numbers[0];

foreach $i (@numbers[1..$#numbers])
{
	if ($i > $max)
	{
		$max = $i;
	}
	elsif ($i < $min)
	{
		$min = $i;
	}
}

print "The maximum is " . $max . "\n";
print "The minimum is " . $min . "\n";

The foreach loop in the example assigns each of the elements of the array which was passed to it to $i in turn, and executes the same set of commands for each value.


Written by Shlomi Fish