跳至內容

Rexx 程式設計/如何使用 Rexx/goto

來自華夏公益教科書,面向開放世界的開放書籍

許多語言都有一個“jump”指令或“goto”語句,用於跳至程式的任意部分。其他語言透過更特定的流程控制結構完全取代了對這種語句的需求。Rexx 主要使用子例程和 DO/END 塊來跳轉到程式的不同部分,但它確實有一種更通用的跳轉指令。你可以使用 SIGNAL 關鍵字將計算機重定向到程式中帶標籤的位置。標籤以冒號結尾。

/* Jump around to validate input and factor a whole number. */
START:
 say "I can factor a positive whole number for you."
 say "First, enter a number of your choice:"
 signal GET_NUMBER
START_FACTORING:
 say "Here are the factors of" number":"
 possible_factor = 1
CHECK_FACTOR:
 if number // possible_factor = 0 then signal SHOW_FACTOR
 else signal NEXT_FACTOR
SHOW_FACTOR:
 say possible_factor
NEXT_FACTOR:
 possible_factor = possible_factor + 1
 if possible_factor > number then signal FINISHED
 signal CHECK_FACTOR
FINISHED:
 say "That's all!"
 exit
GET_NUMBER:
 pull number
CHECK_NUMBER:
 if DataType(number, "W") then signal POSITIVE?
 say "That's not even a whole number."
 signal GET_NUMBER
POSITIVE?:
 if number > 1 then signal START_FACTORING
 say "Positive, please!"
 signal GET_NUMBER

依賴 goto 語句的長程式眾所周知從長期來看很難理解。堅持使用本書其他地方所述的結構化流程控制語句,比如 for 迴圈。編寫此指令碼的一種更簡潔的方式(無需 SIGNAL 語句)如下

/* Greet the user and ask for a positive whole number. */
say "I can factor a positive whole number for you!"
say "First, enter a number of your choice:"
/* Make sure the user actually enters a positive whole number. */
do until whole? & positive?
 pull number
 whole? = DataType(number, "W")
 positive? = number > 0
 if \ whole? then say "That's not even a number!"
 else if \ positive? then say "Positive, please!"
end
/* Now show the factors */
say "Here are the factors of" number":"
do possible_factor = 1 to number
 if number // possible_factor = 0 then
  say possible_factor
end
say "That's all!"
exit
華夏公益教科書