Perl 循环嵌套
Perl 语言允许在一个循环内使用另一个循环,下面是几种嵌套循环的写法
嵌套循环语句语法
嵌套 for 循环语句的语法:
for ( init; condition; increment ){ for ( init; condition; increment ){ statement(s); } statement(s); }
嵌套 while 循环语句的语法:
while(condition){ while(condition){ statement(s); } statement(s); }
嵌套 do...while 循环语句的语法:
do{ statement(s); do{ statement(s); }while( condition ); }while( condition );
嵌套 until 循环语句的语法:
until(condition){ until(condition){ statement(s); } statement(s); }
嵌套 foreach 循环语句的语法:
foreach $a (@listA){ foreach $b (@listB){ statement(s); } statement(s); }
范例 : Perl 嵌套循环的使用
#!/usr/bin/perl =pod file: mail.pl author: 简单教程(www.twle.cn) Copyright © 2015-2065 www.twle.cn. All rights reserved. =cut $x = 0; $y = 0; # 外部循环 while($x < 3){ $y = 0; # 内部循环 while( $y < 3 ){ print "x = $x, y = $y\n"; $y += 1; } $x += 1; print "x = $x\n\n"; }
运行以上范例,输出结果为:
$ perl main.pl x = 0, y = 0 x = 0, y = 1 x = 0, y = 2 x = 1 x = 1, y = 0 x = 1, y = 1 x = 1, y = 2 x = 2 x = 2, y = 0 x = 2, y = 1 x = 2, y = 2 x = 3