Search iEntry News

PERL Loops

By Bryan Young
Expert Author
Article Date: 2010-06-15

There are several different flavors of loops available when coding in PERL. The four most commonly used loops are the while loop, the until loop, the for loop, and the foreach loop. Below you will find a quick tutorial on how each is used.

The While Loop

The while loop is used the same way in PERL as the rest of the mainstream programming languages. Simply put you are testing a condition and while that condition returns true, the looped code is continually ran.

$count = 1;
while ($count <= 5)
{
print "$count, ";
$count++;
}
print "six!";

This will output "1, 2, 3, 4, 5, six!"

The Until Loop

The until loop is the logical opposite of the while loop. The condition is tested, and as long as the condition tests false, the code is repeated.

$count = 1;
until ($count == 5)
{
print "$count, ";
$count++;
}
print "six!";

This will output "1, 2, 3, 4, six!" Once the condition is met, the code sequence immediately picks up at the statement following the loop.

The For Loop

The for loop is basically a while loop with a built in counter. You initialize the counter variable, give the condition for the loop, and also the increment to be used all in one line of code.

for ($i = 0; $i < 10; $i += 2)
{
print "$i, ";
}
print "done!";

This loop will output "0, 2, 4, 6, 8, done!" The built in counter is useful when you know beforehand how many times you want the loop to propogate.

The Foreach Loop

The foreach loop is used exclusively when dealing with arrays. This loop will execute its code once for each element in the provided array. Let's initialize an array and print each element separated by a comma.

@array = ("element1", "element2", "element3");
foreach $element (@array)
{
print "$element ";
}

This will output "element1 element2 element3 ". You will notice the $element variable placed before the parenthesis. This variable stores the value of each index from the array as the loop processes.



About the Author:
Bryan Young is a staff writer for WebProNews.




Newsletter Archive | Article Archive | Submit Article | Advertising Information | About Us | Contact

PerlProNews is an iEntry, Inc. ® publication - All Rights Reserved Privacy Policy and Legal