Perl goto 語句



Perl 支援 goto 語句。有三種形式:goto LABEL、goto EXPR 和 goto &NAME。

序號 goto 型別
1

goto LABEL

goto LABEL 形式跳轉到用 LABEL 標記的語句,並從那裡繼續執行。

2

goto EXPR

goto EXPR 形式只是 goto LABEL 的泛化。它期望表示式返回一個標籤名稱,然後跳轉到該標記的語句。

3

goto &NAME

它用命名子程式的呼叫替換當前正在執行的子程式。

語法

goto 語句的語法如下:

goto LABEL

or

goto EXPR

or

goto &NAME

流程圖

Perl goto statement

示例

以下程式顯示了 goto 語句最常用的形式:

#/usr/local/bin/perl
   
$a = 10;

LOOP:do {
   if( $a == 15) {
      # skip the iteration.
      $a = $a + 1;
      # use goto LABEL form
      goto LOOP;
   }
   print "Value of a = $a\n";
   $a = $a + 1;
} while( $a < 20 );

執行以上程式碼時,會產生以下結果:

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

以下示例顯示了 goto EXPR 形式的用法。這裡我們使用兩個字串,然後使用字串連線運算子 (.) 連線它們。最後,它形成一個標籤,並且使用 goto 跳轉到該標籤:

#/usr/local/bin/perl
   
$a = 10;
$str1 = "LO";
$str2 = "OP";

LOOP:do {
   if( $a == 15) {
      # skip the iteration.
      $a = $a + 1;
      # use goto EXPR form
      goto $str1.$str2;
   }
   print "Value of a = $a\n";
   $a = $a + 1;
} while( $a < 20 );

執行以上程式碼時,會產生以下結果:

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
perl_loops.htm
廣告