Perl 循環(huán)嵌套

Perl 循環(huán) Perl 循環(huán)

Perl 語言允許在一個循環(huán)內(nèi)使用另一個循環(huán),下面演示幾個實例來說明這個概念。

語法

嵌套 for 循環(huán)語句的語法:

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

嵌套 while 循環(huán)語句的語法:

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

嵌套 do...while 循環(huán)語句的語法:

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

}while( condition );

嵌套 until 循環(huán)語句的語法:

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

嵌套 foreach 循環(huán)語句的語法:

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

實例

#!/usr/bin/perl

$a = 0;
$b = 0;

# 外部循環(huán)
while($a < 3){
   $b = 0;
   # 內(nèi)部循環(huán)
   while( $b < 3 ){
      print "a = $a, b = $b\n";
      $b = $b + 1;
   }
   $a = $a + 1;
   print "a = $a\n\n";
}

執(zhí)行以上程序,輸出結(jié)果為:

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 循環(huán) Perl 循環(huán)