Perl for loop

Perl for loop Perl loop

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

Grammar

The syntax format looks like this:

for ( init; condition; increment ){
   statement(s);
}

Here is the control process resolution for the loop:

  1. Init is executed first and only once. T his step allows you to declare and initialize any loop control variables. You can also write no statements here, as long as a sign appears.
  2. Next, you'll judge the condition. I f true, the loop body is executed. If false, the loop body is not executed, and the control flow jumps to the next statement immediately after the for loop.
  3. After executing the for loop body, the control flow jumps back to the increment statement above. T his statement allows you to update the loop control variable. The statement can be left blank as long as a sign appears after the condition.
  4. Conditions are judged again. I f true, the loop is executed, a process that repeats over and over again (the loop body, then increases the step value, and then re-determines the condition). When the condition changes to false, the for loop terminates.

Here, statement(s) can be a separate statement or a block of code consisting of several statements. Condition can be any expression that executes a loop when the condition is false.

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

Flow chart

Perl for loop

Instance

#!/usr/bin/perl

# 执行 for 循环
for( $a = 0; $a < 10; $a = $a + 1 ){
    print "a 的值为: $a\n";
}

The above procedure is performed and the output is:

a 的值为: 0
a 的值为: 1
a 的值为: 2
a 的值为: 3
a 的值为: 4
a 的值为: 5
a 的值为: 6
a 的值为: 7
a 的值为: 8
a 的值为: 9

Perl for loop Perl loop