Latest web development tutorials

Perl for loop

Perl cycle Perl cycle

Perl for loop is used to execute a sequence of statements repeatedly, simplify code management loop variable.

grammar

The syntax is as follows:

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

Here is the control flow for the cycle analysis:

  1. init is executed first, and only once.This step allows you to declare and initialize any loop control variables. You can also write any statement that is not here, as long as there is a semicolon to appear.
  2. Next, we will judgecondition.If true, the loop body is executed. If false, the loop body is not executed, and the control flow jumps to immediately for the next statement cycle.
  3. After executing the for loop body, control flow jumps back aboveincrement statement.This statement allows you to update the loop control variable. The statement can be left blank, as long as the conditions appear to have a semicolon.
  4. Condition is judged again. If true, then the execution cycle, the process is repeated (loop body, and then increase the step value, then to re-determine the conditions). When the condition becomes false, for loop terminates.

Here, statement (s) may be a single statement, it can also be a block composed of a few statements. condition can be any expression, when the condition is false the loop.

When the condition is true, program flow will continue with the next statement followed the loop.

flow chart

Perl for loop

Examples

#!/usr/bin/perl

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

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 cycle Perl cycle