Perl FOR EACH Loop Function

What is For Each loop function in Perl programming?

Explanation

The For Each loop statement in Perl is used with array to manipulate array elements to get the desired result.

Syntax:

foreach variable ( array )
{
Statement to be executed
}

In the above syntax for each occurence of the "variable" the "array" is checked, if "true" the code segement given below is executed.

Example :


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$search = "Kate";
@actress = ("Angelina", "Pamela", "Katrina", "Jennifer", "Kate");
foreach $name (@actress)
{
if ($name eq $search)
{
$prompt = "$name listed!n";
print $prompt;
print "
";
}
else
{
$prompt = "$name not listed!n";
print $prompt;
print "
";
}
}
Result :

Angelina not listed!
Pamela not listed!
Katrina not listed!
Jennifer not listed!
Kate listed!

In the above example the variable "$name" is checked if its equal to the variable "$search" with the elements of the array "@actress", it displays the listed and not listed actress names.

Ask Questions

Ask Question