Rexx 程式設計/Rexx 指南/迴圈
外觀
迴圈是控制結構,允許程式碼段根據迴圈的控制條件重複執行。Rexx 指令碼語言支援迭代迴圈和條件迴圈。
迭代迴圈在迭代器遍歷一系列值時,重複執行一組指令。迭代迴圈的型別包括 for 迴圈和 foreach 迴圈。以下是一個傳統的迭代 for 迴圈示例
do count = 1 to 10 say count end
在上面的示例中,say 塊執行十次,迭代器變數count在每次連續迴圈中遞增。
當迭代迴圈逐步迴圈其程式碼時,可以將迭代器變數增加的值設定為 1 以外的數字。by 關鍵字位於每次迭代要增加的值之前。
/* Count by 2's */ do count = 2 to 10 by 2 say count end
或者,可以使用for 關鍵字告訴 Rexx 迭代迴圈的次數。我們可以列出前 20 個正奇數,如下所示
do count = 1 by 2 for 20 say count end
條件迴圈測試迴圈周圍的條件,並在條件為真時重複執行一組指令。條件迴圈的型別包括 while 迴圈和 until 迴圈。
count = 0 do while count <= 10 say count count = count + 1 end
while 迴圈只有在條件為真時才會啟動。
/* Nothing happens! */ count = 100 do while count <= 10 say "Whatever, you're not going to see this message anyway." end
Until 迴圈用於啟動程式碼塊,並在滿足某些條件之前繼續執行。
/* Ask the user to enter a number until they actually do. */ do until entry_is_valid say "Please enter a number below." pull entry entry_is_valid = datatype(entry, "NUM") end /* The user will always be asked at least once. */
迭代迴圈和條件迴圈都可以透過迴圈修改語句來控制,例如 leave、iterate 和 signal(我們還有 next、last 和 redo 嗎?)。這些允許迴圈內的正常執行流程重新啟動或終止。
LEAVE 指令停止迴圈。
/* This function will keep adding up numbers as long the user keeps entering them. */
say "Enter as many numbers as you want!"
say "Put each one on a line by itself."
total = 0
do forever
entry = LineIn()
if DataType(entry) = "NUM" then
say "Cool, you entered another number!"
else
leave
total = total + entry
say "The new total is" total"."
end
say "The final total is" total"."
ITERATE 指令跳到下一步,而不完成當前步驟。
/* Let's pretend 3 and 4 are boring. */
do number = 1 to 5
if number = 3 then iterate
if number = 4 then iterate
say "I found an interesting number. It is" number"."
say "Do you agree that it is interesting?"
answer = LineIn()
if answer = "yes" then do
say "I'm glad you agree."
say "Good thing it wasn't 3 or 4."
end
end
Rexx 指令碼語言允許使用巢狀迴圈結構。這些結構由一個或多個巢狀在其他迴圈中的迴圈組成。