Perl loop nesting


Release date:2023-10-17 Update date:2023-10-21 Editor:admin View counts:289

Label:

Perl loop nesting

Perl language allows the use of another loop within one loop, and here are a few examples to illustrate this concept.

Grammar

Nesting for syntax of the loop statement:

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

Nesting while syntax of the loop statement:

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

Nesting do...while syntax of the loop statement:

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

Nesting until the syntax of the loop statement:

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

Nesting foreach syntax of the 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;#
Internal circulation while($b<3){print"a =$a, b =$b\\n";$b=$b+1;}$a=$a+1;print"a
=$a\\n\\n";}

Execute the above program, and the output is as follows:

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

Powered by TorCMS (https://github.com/bukun/TorCMS).