switch语句可以让一个变量值的列表进行相等测试。每个值被称为一个的情况(case),该变量被接通检查每个switch case。
Tcl语言未加引号的switch语句的语法如下:
switch switchingString matchString1 {body1} matchString2 {body2} ... matchStringn {bodyn} |
Tcl语言未加引号的switch语句的语法如下:
switch switchingString { |
matchString1 { |
body1 |
} |
matchString2 { |
body2 |
} |
... |
matchStringn { |
bodyn |
} |
} |
以下规则适用于switch语句:
在switch语句中使用的switchingString通过比较matchString使用在不同块之间。
在一个switch内可以任何数量matchString块。
switch语句可以具有可选默认块,其中必须出现在开关的末尾。缺省情况下,可用于执行任务时没有一个case是真实的。
例如:未加引号版本
#!/usr/bin/tclsh |
set grade C; |
switch $grade A { puts "Well done!" } B { puts "Excellent!" } C { puts "You passed!" } F { puts "Better try again" } default { puts "Invalid grade" } |
puts "Your grade is $grade" |
You passed! |
Your grade is C |
#!/usr/bin/tclsh |
set grade B; |
switch $grade { |
A { |
puts "Well done!" |
} |
B { |
puts "Excellent!" |
} |
C { |
puts "You passed!" |
} |
F { |
puts "Better try again" |
} |
default { |
puts "Invalid grade" |
} |
} |
puts "Your grade is $grade" |
Well done Your grade is B