Foreach Loop

Domain Hosting image
Web Hosting
Dedicated server
ssl certificate
Web Design image
Email

Besides while, until, and for, Perl provides the foreach statement to execute a block of code for each element in an array. Of course, you could use a for loop to access each element of an array but its index, but it's much simpler to access each array element with the foreach statement.

The goal is to find the largest number in an array of numbers. Here's how you might write such a program using a foreach loop:

#!usr/local/bin/perl
#define an array of numbers
@scores = (65,49,67,25,82,64,70,73);
#Loop through array and find highest score
foreach $score(@scores)
{
if($score>$max)
{
$max=$score;
}
}
#print the highest score
print "Highest Score =$max\n";

If you compare the foreach loop with the for loop for processing elements of array, you'll notice that the foreach loop looks simpler because you do not to use any array index to access the elements of the array. This eliminate occurences of expressions such as $scores[$i].



Domain Name Search

www.


Copyright (C) 2007. Web Domain design hosting. All rights reserved.