如何将可选参数传递给tcl进程?

如何将可选参数传递给tcl进程?,tcl,Tcl,我试图开发一个tcl过程,它的第二个参数将是可选参数。如果可选的参数值是-f,那么我只想处理这个参数,就像处理主体一样。但是,如果是-h,那么我想查询参数的值,如下所示 compare_run ARG1 -f compare_run ARG1 -h <val> compare_run ARG1 -a compare\u运行ARG1-f 比较运行ARG1-h 比较运行ARG1-a 您能给我一个示例代码来检查类似的内容吗?您有两种方法可以使用proc执行可选参数;指定默认值或使

我试图开发一个tcl过程,它的第二个参数将是可选参数。如果可选的参数值是-f,那么我只想处理这个参数,就像处理主体一样。但是,如果是-h,那么我想查询参数的值,如下所示

 compare_run ARG1 -f
 compare_run ARG1 -h <val>
 compare_run ARG1 -a
compare\u运行ARG1-f
比较运行ARG1-h
比较运行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
见本报告第三段