在解析命令行选项时,最简单的方法是有一个简单的阶段将所有这些分开并将其变成更易于在其余代码中使用的东西。或许是这样的:
# Deal with mandatory first argument
if {$argc < 1} {
puts stderr "Missing filename"
exit 1
}
set filename [lindex $argv 0]
# Assumes exactly one flag value per option
foreach {key value} [lrange $argv 1 end] {
switch -glob -- [string tolower $key] {
-spec {
# Might not be the best choice, but it gives you a cheap
# space-separated list without the user having to know Tcl's
# list syntax...
set RElist [split $value]
}
-* {
# Save other options in an array for later; might be better
# to do more explicit parsing of course
set option([string tolower [string range $key 1 end]]) $value
}
default {
# Problem: option doesn't start with hyphen! Print error message
# (which could be better I suppose) and do a failure exit
puts stderr "problem with option parsing..."
exit 1
}
}
}
# Now you do the rest of the processing of your code.
然后您可以检查是否有任何 RE 匹配一些字符串,如下所示:
proc anyMatches {theString} {
global RElist
foreach re $RElist {
if {[regexp $re $theString]} {
return 1
}
}
return 0
}