Latest web development tutorials

Perl 循環嵌套

Perl 循環 Perl循環

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

語法

嵌套for 循環語句的語法:

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

嵌套while 循環語句的語法:

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

嵌套do...while 循環語句的語法:

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

}while( condition );

嵌套until 循環語句的語法:

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

嵌套foreach 循環語句的語法:

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

實例

#!/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";
}

執行以上程序,輸出結果為:

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 循環 Perl循環