如何安全地处理可选参数 [英] How can I safely deal with optional parameters
问题描述
我正在编写一个过程来在输出文件中创建一个标题.
I am writing a proc to create a header in an output file.
目前它需要带一个可选参数,这是标题的可能注释.
Currently it needs to take an optional parameter, which is a possible comment for the header.
我最终将其编码为单个可选参数
I have ended up coding this as a single optional parameter
proc dump_header { test description {comment = ""}}
但想知道如何使用 args 实现相同的效果
but would like to know how I can achieve the same using args
proc dump_header { test description args }
检查 args 是否为单个空白参数 ($args == "") 非常容易,但如果传递多个参数则无法很好地处理 - 无论如何我都需要否定检查.
It's quite easy to check for args being a single blank parameter ($args == ""), but doesn't cope well if passing multiple parameters - and I need the negative check anyway.
推荐答案
您的 proc 定义不正确(您会收到错误消息 too many fields in argument specifier "comment = """
).应该是:
Your proc definition is incorrect (you'd get the error message too many fields in argument specifier "comment = """
). Should be:
proc dump_header { test description {comment ""}} {
puts $comment
}
如果你想使用args
,你可以检查它的llength
:
If you want to use args
, you could examine the llength
of it:
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]"
}
}
}
您可能还想在列表中传递名称-值对:
You might also want to pass name-value pairs in a list:
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}
有些人更喜欢 args
和名称-值对(a la Tk)的组合
Some prefer a combination of args
and name-value pairs (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
这篇关于如何安全地处理可选参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!