如何安全地处理可选参数

itj*_*itj 6 tcl

我正在写一个proc来在输出文件中创建一个标题.

目前,它需要采用可选参数,这是标题的可能注释.

我最终将其编码为单个可选参数

proc dump_header { test description {comment = ""}}
Run Code Online (Sandbox Code Playgroud)

但是我想知道如何使用args实现相同的目标

proc dump_header { test description args }
Run Code Online (Sandbox Code Playgroud)

检查args是否是一个空白参数($ args =="")非常容易,但是如果传递多个参数则不能很好地应对 - 而且我还需要负面检查.

gle*_*man 13

您的proc定义不正确(您将收到错误消息too many fields in argument specifier "comment = """).应该:

proc dump_header { test description {comment ""}} {
    puts $comment
}
Run Code Online (Sandbox Code Playgroud)

如果你想使用args,你可以检查llength它:

proc dump_header {test desc args} {
    switch -exact [llength $args] {
        0 {puts "no comment"}
        1 {puts "the comment is: $args"}
        default {
            puts "the comment is: [lindex $args 0]"
            puts "the other args are: [lrange $args 1 end]"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能还想在列表中传递名称 - 值对:

proc dump_header {test desc options} {
    # following will error if $options is an odd-length list
    array set opts $options

    if {[info exists opts(comment)]} {
        puts "the comment is: $opts(comment)"
    }
    puts "here are all the options given:"
    parray opts
}
dump_header "test" "description" {comment "a comment" arg1 foo arg2 bar}
Run Code Online (Sandbox Code Playgroud)

有些人更喜欢组合args和名称 - 价值对(a la Tk)

proc dump_header {test desc args} {
    # following will error if $args is an odd-length list
    array set opts $args
    if {[info exists opts(-comment)]} {
        puts "the comment is: $opts(-comment)"
    }
    parray opts
}
dump_header "test" "description" -comment "a comment" -arg1 foo -arg2 bar
Run Code Online (Sandbox Code Playgroud)


Tre*_*son 5

我使用tcllibcmdline库来进行选项解析.

这是cmdline文档中的示例:

set options {
    {a          "set the atime only"}
    {m          "set the mtime only"}
    {c          "do not create non-existent files"}
    {r.arg  ""  "use time from ref_file"}
    {t.arg  -1  "use specified time"}
}
set usage ": MyCommandName \[options] filename ...\noptions:"
array set params [::cmdline::getoptions argv $options $usage]

if {  $params(a) } { set set_atime "true" }
set has_t [expr {$params(t) != -1}]
set has_r [expr {[string length $params(r)] > 0}]
if {$has_t && $has_r} {
    return -code error "Cannot specify both -r and -t"
} elseif {$has_t} {
    ...
}
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,您只需使用args代替argv上面的示例.