Perl nested loop
Perl language allows the use of another loop within a loop below demonstrates several examples to illustrate this concept.
grammar
Nested for loop syntax:
for ( init; condition; increment ){ for ( init; condition; increment ){ statement(s); } statement(s); }
Nested while loop syntax:
while(condition){ while(condition){ statement(s); } statement(s); }
Nested do ... while loop syntax statements:
do{ statement(s); do{ statement(s); }while( condition ); }while( condition );
Until nested loop syntax:
until(condition){ until(condition){ statement(s); } statement(s); }
Nested foreach loop syntax:
foreach $a (@listA){ foreach $b (@listB){ statement(s); } statement(s); }
Examples
#!/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 program, 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