Jas*_*rne 2 list tcl switch-statement
我对tcl中switch的使用有疑问.主要是,我想知道是否有可能做出类似的事情:
switch myvar {
list1 {
puts "myvar matches contents of list1"; }
list2 {
puts "myvar matches contents of list2"; }
default {
puts "myvar doesn't match any content of any list"; }
}
Run Code Online (Sandbox Code Playgroud)
在这里,list1和list2可以是包含不同文件名称的列表或字符串数组.
如果没有进行非常详细的正则表达式搜索,这是否可行?
谢谢!
您可以轻松地将其重写为if elseif else构造,正如Brian Fenton已经说过的那样(并使用'in'运算符来简化它.
if {$myvar in $list1} {
puts "myvar matches content of list"
} elseif {$myvar in $list2} {
puts "myvar matches content of list2"
} elseif {
puts "myvar doesn't match any content of any list"
}
Run Code Online (Sandbox Code Playgroud)
您当然可以将代码包装起来并编写自己的开关版本来完成您想要的任务,毕竟这是Tcl ......
proc listswitch {item conditions} {
if {[llength $conditions] % 2} {
return -code error "Conditions must be pairs"
}
set code ""
foreach {cond block} $conditions {
if {$cond eq "default"} {
set code $block
break
} elseif {$item in $cond} {
set code $block
break
}
}
if {$code ne ""} {
uplevel 1 $code
}
}
listswitch 10 {
{10 20 30 50} {
puts "Match in list 1" }
{50 20 90 11} {
puts "Match in list 2"
}
default {
puts "No match"
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想要字面上匹配文件名,或者你感兴趣的是什么样的平等,你需要担心一点.有一些微妙的东西,如不区分大小写的文件系统,不同的目录分隔符,绝对与相对,甚至文件系统编码等可能会改变结果的东西.