Perl loop nesting

Perl loop nesting Perl loop

The Perl language allows another loop to be used in one loop, and here are a few examples to illustrate the concept.

Grammar

The syntax of nesting for loop statements:

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

The syntax of nesting while loop statements:

while(condition){
   while(condition){
      statement(s);
   }
   statement(s);
}

Nested do... The syntax of the while loop statement:

do{
   statement(s);
   do{
      statement(s);
   }while( condition );

}while( condition );

The syntax of nested until loop statements:

until(condition){
   until(condition){
      statement(s);
   }
   statement(s);
}

The syntax of nesting foreach loop statements:

foreach $a (@listA){
   foreach $b (@listB){
      statement(s);
   }
   statement(s);
}

Instance

#!/usr/bin/perl

$a = 0;
$b = 0;

# 外部循环
while($a < 3){
   $b = 0;
   # 内部循环
   while( $b < 3 ){
      print "a = $a, b = $b\n";
      $b = $b + 1;
   }
   $a = $a + 1;
   print "a = $a\n\n";
}

The above procedure is performed and the output is:

a = 0, b = 0
a = 0, b = 1
a = 0, b = 2
a = 1

a = 1, b = 0
a = 1, b = 1
a = 1, b = 2
a = 2

a = 2, b = 0
a = 2, b = 1
a = 2, b = 2
a = 3

Perl loop nesting Perl loop