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

Perl for Loop

Perl for Loop

Perl Loops Perl Loops

The Perl for loop is used to execute a sequence of statements multiple times, simplifying the code for managing loop variables.

Syntax

The syntax format is as follows:



for ( init; condition; increment ){

   statement(s);

}

The following is an analysis of the for loop's control flow:

  1. init is executed first and only once. This step allows you to declare and initialize any loop control variables. You may also write no statement here, as long as a semicolon appears.
  2. Next, the condition. If true, the loop body is executed. If false, the loop body is not executed, and control flows to the next statement immediately following the for loop.
  3. After executing the for loop body, control flow jumps back to the above increment statement. This statement allows you to update the loop control variable. This statement can be left empty, as long as a semicolon appears after the condition.
  4. The condition is evaluated again. If true, the loop executes, and this process repeats (loop body, then increment the step value, then re-evaluate the condition). When the condition becomes false, the for loop terminates.

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 and exits when the condition is false.

Flowchart

The for Loop in Perl

Example

#!/usr/bin/perl

Executing the for loop

for

(

$a

=

0

;

$a

<

10

;

$a

=

$a

1

)

{

print

"

The value of a is:

$a

\n

"

;

}

Running the above program, the output is:



a 的值为: 0

a 的值为: 1

a 的值为: 2

a 的值为: 3

a 的值为: 4

a 的值为: 5

a 的值为: 6

a 的值为: 7

a 的值为: 8

a 的值为: 9

Perl Loops Perl Loops