Perl while loop

Perl 循环Perl Loops

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

Syntax

The syntax format is as follows:

while(condition)
{
   statement(s);
}

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

condition can be any expression. When the condition is true, the loop executes. When the condition is false, the program flow will exit the loop.

Flowchart

Perl 中的 while 循环

In the diagram,whileThe key point of the loop is that the loop may not execute even once. When the condition is false, the loop body is skipped, and the next statement after 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; }

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

Executing the above program produces the following output:

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

Perl 循环Perl Loops

Other Extensions