如何将可选参数传递给 tcl proc?
How to pass the optional arguments to a tcl proc?
我正在尝试开发一个 tcl 过程,其第二个参数将是一个可选参数。如果可选参数值为 -f,那么我只想处理该参数,因为它是正文。但是,如果它是 -h 那么我也想查询该参数的值,如下所示
compare_run ARG1 -f
compare_run ARG1 -h <val>
compare_run ARG1 -a
你能给我一个示例代码来检查类似的东西吗?
你有两种方法可以用 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
我正在尝试开发一个 tcl 过程,其第二个参数将是一个可选参数。如果可选参数值为 -f,那么我只想处理该参数,因为它是正文。但是,如果它是 -h 那么我也想查询该参数的值,如下所示
compare_run ARG1 -f
compare_run ARG1 -h <val>
compare_run ARG1 -a
你能给我一个示例代码来检查类似的东西吗?
你有两种方法可以用 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