Perl Nested Loops
The Perl language allows one loop to be used inside another loop. The following examples demonstrate this concept.
Syntax
The syntax of a nested for loop statement:
for ( init; condition; increment ){
for ( init; condition; increment ){
statement(s);
}
statement(s);
}
The syntax of a nested while loop statement:
while(condition){
while(condition){
statement(s);
}
statement(s);
}
The syntax of a nested do...while loop statement:
do{
statement(s);
do{
statement(s);
}while( condition );
}while( condition );
The syntax of a nested until loop statement:
until(condition){
until(condition){
statement(s);
}
statement(s);
}
The syntax of a nested foreach loop statement:
foreach $a (@listA){
foreach $b (@listB){
statement(s);
}
statement(s);
}
Examples
#!/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 produces 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 = 3Other Extensions
Perl Loops