我正在尝试开发一个 tcl 过程,它的第二个参数将是一个可选参数。如果可选参数值为 -f,那么我只想处理该参数,因为它对主体而言。但是,如果它是 -h 那么我想查询该参数的值也如下
compare_run ARG1 -f
compare_run ARG1 -h <val>
compare_run ARG1 -a
你能不能给我一个示例代码来检查类似的东西?
答案 0 :(得分:0)
您有两种使用 proc
处理可选参数的方法;要么指定默认值,要么使用 args
特殊参数。听起来这是您想要的第二种情况。为了获得您的确切模式(或其明显的扩展),您需要对该列表进行一些处理。
proc compare_run {firstArgument args} {
array set options {-f 0 -a 0 -h ""}
while {[llength $args]} {
# Pop the first value into $opt
set args [lassign $args opt]
# You'd do abbreviation processing here if you needed it: see [tcl::prefix]
switch $opt {
"-f" - "-a" {
# Boolean options
set options($opt) 1
}
"-h" {
# Argumented options
if {![llength $args]} {error "where's the value for $opt?"}
set args [lassign $args options($opt)]
}
default {
error "unknown option: $opt"
}
}
}
# Now you parsed all the options; show this (or replace with something real)
puts "firstArgument = $firstArgument"
parray options
}
人们多年一直在讨论如何制作一个更正式的版本,但从未达成一致。最常见的做法(因为它简短且易于编写)就是将 args 视为字典并将其与默认值合并:
proc compare_run_2 {firstArgument args} {
array set options {-f 0 -a 0 -h ""}
array set options $args
# Also see dictionaries:
# set options [dict merge {-f 0 -a 0 -h ""} $args]
puts "firstArgument = $firstArgument"
parray options
}
但这有一个稍微不同的调用模式,如下所示:
compare_run_2 -f 1