Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Perl Nested Loops

Perl Nested Loops

Perl Loops Perl Loops

The Perl language allows one loop to be used inside another; 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

)

;

}

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

"

;

}

Running the above program, the output is:



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 Loops