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){
foreachb (@listB){
statement(s);
}
statement(s);
}
实例
#!/usr/bin/perl
a = 0;b = 0;
# 外部循环
while(a<3){b = 0;
# 内部循环
while( b<3 ){
print "a =a, b = b\n";b = b + 1;
}a = a + 1;
print "a =a\n\n";
}
执行以上程序,输出结果为:
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