Easy Tutorial
❮ Perl Unless Elsif Statement Perl Switch Statement ❯

Perl Loop Nesting

Perl Loops

The Perl language allows the use of one loop inside another loop. Below are several examples demonstrating this concept.

Syntax

Syntax for nested for loop statements:

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

Syntax for nested while loop statements:

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

Syntax for nested do...while loop statements:

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

}while( condition );

Syntax for nested until loop statements:

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

Syntax for nested foreach loop statements:

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

Example

#!/usr/bin/perl

$a = 0;
$b = 0;

# Outer loop
while($a < 3){
   $b = 0;
   # Inner loop
   while( $b < 3 ){
      print "a = $a, b = $b\n";
      $b = $b + 1;
   }
   $a = $a + 1;
   print "a = $a\n\n";
}

Executing the above program will produce the following output:

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 Loops

❮ Perl Unless Elsif Statement Perl Switch Statement ❯