Perl nested Loop

Advertisements


A loop can be nested inside of another loop. Perl allows to nest all type of loops to be nested.

Syntax:

The syntax for a nested for loop statement in Perl is as follows:

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

The syntax for a nested while loop statement in Perl is as follows:

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

The syntax for a nested do...while loop statement in Perl is as follows:

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

}while( condition );

The syntax for a nested until loop statement in Perl is as follows:

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

The syntax for a nested foreach loop statement in Perl is as follows:

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

Example:

The following program uses a nested while loop to show the usage:

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

This would produce following result:

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


Advertisements
Advertisements