1. Technology

while loop - Beginning Perl Tutorial, Control Structures

How to use a while loop in Perl


Next: Examples of Perl's while loop

Perl's while loop, is used to loop through a designated block of code while a specific condition is evaluated as true.

 while (expression) {
Perl starts the block by evaluating the expression inside the parenthesis. If the expression evaluates as true the code is executed, and will continue to execute in a loop until the expression evaluates as false. If the expression initially evaluates to false, the code is never executed and the while block will be skipped entirely.

The while loop process looks something like this when you break down each of the steps:

  1. Evaluate the initial expression.
  2. Does the test evaluate to true? If so, continue, otherwise exit the while loop.
  3. Execute the code block inside the while loop.
  4. Return to step 2.
Unlike the for loop, the while loop does not have a self-contained way to alter the initial expression. Be careful that your Perl script does not wind up in a continuous while loop and lock up or crash.

Next: Examples of Perl's while loop

  1. About.com
  2. Technology
  3. Perl
  4. Perl Tutorials
  5. Perl while loop tutorial - Control structures in Perl

©2014 About.com. All rights reserved.