Perl while loop

Perl while loop Perl loop

When a while statement repeats a statement or group of statements when a given condition is true. The condition is tested before the loop body executes.

Grammar

The syntax format looks like this:

while(condition)
{
   statement(s);
}

Here, statement(s) can be a separate statement or a block of code consisting of several statements. C ondition can be any expression, true when it is any non-zero value. The loop is executed when the condition is true.

When the condition is false, the program flow continues to execute the next statement immediately after the loop.

Flow chart

Perl while loop

In the chart, the key point of the while loop is that the loop may not execute once. When the condition is false, the loop body is skipped and the next statement immediately following the while loop is executed.

Instance

#!/usr/bin/perl

$a = 10;

# 执行 while 循环
while( $a < 20 ){
   printf "a 的值为 : $a\n";
   $a = $a + 1;
}

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

The above procedure is performed and the output is:

a 的值为 : 10
a 的值为 : 11
a 的值为 : 12
a 的值为 : 13
a 的值为 : 14
a 的值为 : 15
a 的值为 : 16
a 的值为 : 17
a 的值为 : 18
a 的值为 : 19

Perl while loop Perl loop