Perl

  1. Home
  2. Computing & Technology
  3. Perl

while loop - Beginning Perl Tutorial, Control Structures

Examples of Perl's while loop

From About.com

As we've discussed, Perl's while loop is used to loop through a designated block of code while a specific condition is evaluated as true. Let's look at an example of Perl's while loop in action and break down exactly how it works, step by step.
$count = 10;
while ($count >= 1) {
print "$count ";
$count--;
}
print "Blastoff.\n";
Running this simple Perl script produces the following output:
10 9 8 7 6 5 4 3 2 1 Blastoff.
First we set the string $count to a value of 10.
$count = 10;
Next comes the start of the while loop, and the expression in the parenthesis is evaluated:
while ($count >= 1)
If the while expression is evaluated as true, the code inside the block is executed and the expression is re-evaluated. When it finally evaluates as false, the block is skipped and the rest of the Perl script is executed.
  1. $count is set to a value of 10.
  2. Is $count greater than or equal to 1? If so, continue, otherwise exit the while loop.
  3. Execute the code block inside the while loop.
  4. Return to step 2.
The end result is that $count starts at 10 and comes down by 1 every time the loop is executed. When we print the value of $count, we can see that the loop is executed while $count has a value of greater than or equal to 1, at which point the loop stops and the word 'Blastoff' is printed.
  1. A while loop is a Perl control structure.
  2. It is used to step through a block of code while a specific condition is true.
Previous: How to use a while loop in Perl

Explore Perl

About.com Special Features

Build Your Own Website

Step-by-step advice on how to do everything from choosing a Web host to promoting your content. More >

Connect Your Home Computers

Easy ways to connect two computers for networking purposes. More >

Perl

  1. Home
  2. Computing & Technology
  3. Perl
  4. Perl Tutorials
  5. Perl while loop tutorial - Control structures in Perl, learn how to use a while loop.

©2009 About.com, a part of The New York Times Company.

All rights reserved.