Perl Next 語句



Perl next 語句開始新一輪迴圈。您可以在 next 語句中提供一個 LABEL,其中 LABEL 是迴圈的標籤。如果未指定 LABEL,則可以在巢狀迴圈中使用 next 語句,其中它將適用於最近的迴圈。

如果迴圈中有 continue 塊,它總是在即將求值的條件之前執行。您將在單獨的章節中看到 continue 語句。

語法

Perl 中 next 語句的語法為 -

next [ LABEL ];

方括號內的 LABEL 表示 LABEL 是可選的,如果未指定 LABEL,則 next 語句將跳轉控制權至最近迴圈的下一輪。

流程圖

Perl next statement

示例

#!/usr/local/bin/perl

$a = 10;
while( $a < 20 ) {
   if( $a == 15) {
      # skip the iteration.
      $a = $a + 1;
      next;
   }
   print "value of a: $a\n";
   $a = $a + 1;
}

當執行以上程式碼時,它將產生以下結果 -

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

我們來舉一個例子,我們將使用一個 LABEL 和 next 語句 -

#!/usr/local/bin/perl

$a = 0;
OUTER: while( $a < 4 ) {
   $b = 0;
   print "value of a: $a\n";
   INNER:while ( $b < 4) {
      if( $a == 2) {
         $a = $a + 1;
         # jump to outer loop
         next OUTER;
      }
      $b = $b + 1;
      print "Value of b : $b\n";
   }
   print "\n";
   $a = $a + 1;
}

當執行以上程式碼時,它將產生以下結果 -

value of a : 0
Value of b : 1
Value of b : 2
Value of b : 3
Value of b : 4

value of a : 1
Value of b : 1
Value of b : 2
Value of b : 3
Value of b : 4

value of a : 2
value of a : 3
Value of b : 1
Value of b : 2
Value of b : 3
Value of b : 4
perl_loops.htm
廣告
© . All rights reserved.