Perl 循环嵌套

Perl 语言允许在一个循环内使用另一个循环,下面演示几个实例来说明这个概念。

语法

嵌套 for 循环语句的语法:

  1. for ( init; condition; increment ){
  2. for ( init; condition; increment ){
  3. statement(s);
  4. }
  5. statement(s);
  6. }

嵌套 while 循环语句的语法:

  1. while(condition){
  2. while(condition){
  3. statement(s);
  4. }
  5. statement(s);
  6. }

嵌套 do…while 循环语句的语法:

  1. do{
  2. statement(s);
  3. do{
  4. statement(s);
  5. }while( condition );
  6. }while( condition );

嵌套 until 循环语句的语法:

  1. until(condition){
  2. until(condition){
  3. statement(s);
  4. }
  5. statement(s);
  6. }

嵌套 foreach 循环语句的语法:

  1. foreach $a (@listA){
  2. foreach $b (@listB){
  3. statement(s);
  4. }
  5. statement(s);
  6. }

实例

  1. #!/usr/bin/perl
  2. $a = 0;
  3. $b = 0;
  4. # 外部循环
  5. while($a < 3){
  6. $b = 0;
  7. # 内部循环
  8. while( $b < 3 ){
  9. print "a = $a, b = $b\n";
  10. $b = $b + 1;
  11. }
  12. $a = $a + 1;
  13. print "a = $a\n\n";
  14. }

执行以上程序,输出结果为:

  1. a = 0, b = 0
  2. a = 0, b = 1
  3. a = 0, b = 2
  4. a = 1
  5.  
  6. a = 1, b = 0
  7. a = 1, b = 1
  8. a = 1, b = 2
  9. a = 2
  10.  
  11. a = 2, b = 0
  12. a = 2, b = 1
  13. a = 2, b = 2
  14. a = 3