Perl 嵌套循环



循环可以嵌套在另一个循环中。Perl 允许嵌套所有类型的循环。

语法

Perl 中嵌套 for 循环语句的语法如下所示 −

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

Perl 中嵌套 while 循环语句的语法如下所示 −

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

Perl 中嵌套 do...while 循环语句的语法如下所示 −

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

}while( condition );

Perl 中嵌套 until 循环语句的语法如下所示 −

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

Perl 中嵌套 foreach 循环语句的语法如下所示 −

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

示例

以下程序使用嵌套while循环来显示用法 −

#/usr/local/bin/perl
   
$a = 0;
$b = 0;

# outer while loop
while($a < 3) {
   $b = 0;
   # inner while loop
   while( $b < 3 ) {
      print "value of a = $a, b = $b\n";
      $b = $b + 1;
   }
   $a = $a + 1;
   print "Value of a = $a\n\n";
}

这将产生以下结果 −

value of a = 0, b = 0
value of a = 0, b = 1
value of a = 0, b = 2
Value of a = 1

value of a = 1, b = 0
value of a = 1, b = 1
value of a = 1, b = 2
Value of a = 2

value of a = 2, b = 0
value of a = 2, b = 1
value of a = 2, b = 2
Value of a = 3
perl_loops.htm
广告