Perl-nested-loops

提供:Dev Guides
移動先:案内検索

Perlネストループ

ループは、別のループ内にネストできます。 Perlでは、すべてのタイプのループをネストすることができます。

構文

Perlでの nested for loop ステートメントの構文は次のとおりです-

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

Perlの nested while loop ステートメントの構文は次のとおりです-

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

Perlの nested do …​ while loop ステートメントの構文は次のとおりです-

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

}while( condition );

Perlでの nested until loop ステートメントの構文は次のとおりです-

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