2013-03-05 32 views
5

我想在我的腳本中有大量的選項。用戶將輸入只能匹配其中一個選項的輸入。我希望能夠有多個不同的選項運行相同的命令,但我似乎無法得到ORs的工作。以下是我認爲它應該是什麼樣子,關於如何使a或b行工作的任何想法?如何在tcl switch語句中使用或?

switch -glob -- $opt { 
    "a" || "b" { 
     puts "you selected a or b, probably not both" 
    } 
    default { 
     puts "Your choice did not match anything" 
    } 
} 

回答

10

您可以使用-作爲案例的主體,將其轉化爲下一個主體,如在Tcl Manual解釋:

如果體被指定爲「 - 」則表示用於下一 圖案身體也應作爲主體此模式(如果下一 圖案還具有「 - 」之後的身體被使用,並且 等)。該功能可以共享 幾種模式中的單個主體。

另外,如果你的選擇是concatentated字符的大串,你將不得不使用通配符來bookend你的選擇模式,或當opt只包含一個選項的情況下,將只匹配:

switch -glob -- $opt { 
    "*a*" - 
    "*b*" { 
     puts "you selected a or b, probably not both" 
    } 
    default { 
     puts "Your choice did not match anything" 
    } 
} 
+0

謝謝,這正是我需要知道的。 – SuperTetelman 2013-03-05 18:40:45

0

也正在此:

switch -regexp -- $opt { 
    a|b { 
     puts "you selected a or b, probably not both" 
    } 
    default { 
     puts "Your choice did not match anything" 
    } 
} 

注意:之間沒有空格 「A | b」