Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Perl while Loop

Perl while Loop

Perl Loops Perl Loops

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

Syntax

The syntax format is as follows:



while(condition)

{

   statement(s);

}

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

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

Flowchart

The while Loop in Perl

In the diagram,while The key point of the loop is that it may not execute even once. When the condition is false, the loop body is skipped and execution proceeds directly to the statement immediately after the while loop.

Example

#!/usr/bin/perl

$a

=

10

;

Executing the while loop

while

(

$a

<

20

)

{

printf

"

The value of a is:

$a

\n

"

;

$a

=

$a

1

;

}

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

Running the above program, the output is:



a 的值为 : 10

a 的值为 : 11

a 的值为 : 12

a 的值为 : 13

a 的值为 : 14

a 的值为 : 15

a 的值为 : 16

a 的值为 : 17

a 的值为 : 18

a 的值为 : 19

Perl Loops Perl Loops