Easy Tutorial
❮ Perl Last Statement Perl Redo Statement ❯

Perl while Loop

Perl Loops

The while statement repeatedly executes a statement or a group of statements as long as the given condition is true. The condition is tested before the loop body is executed.

Syntax

The syntax is as follows:

while(condition)
{
   statement(s);
}

Here, statement(s) can be a single statement or a block of statements.

condition can be any expression, and the loop executes when the condition is true. When the condition is false, the program flow exits the loop.

Flowchart

In the flowchart, the key point of the while loop is that the loop might not run even once. When the condition is false, the loop body is skipped, and the next statement following the while loop is executed directly.

Example

#!/usr/bin/perl

$a = 10;

# Execute while loop
while( $a < 20 ){
   printf "The value of a is : $a\n";
   $a = $a + 1;
}

The program executes the loop body while the variable $a is less than 20, and exits the loop when $a is greater than or equal to 20.

Executing the above program will output:

The value of a is : 10
The value of a is : 11
The value of a is : 12
The value of a is : 13
The value of a is : 14
The value of a is : 15
The value of a is : 16
The value of a is : 17
The value of a is : 18
The value of a is : 19

Perl Loops

❮ Perl Last Statement Perl Redo Statement ❯