您的proc定义不正确(您会收到错误消息too many fields in argument specifier "comment = """
)。应该是:
proc dump_header { test description {comment ""}} {
puts $comment
}
如果你想使用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]"
}
}
}
你可能也想通过名称 - 值对列表:
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)的组合
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
如果你的proc被超过3个参数调用,你想要做什么:dump_header mytest mydesc {One comment} somethingelse?把somethingelse作为另一种评论,以其他方式处理? – 2010-02-26 12:58:36
将$ args与空字符串进行比较是错误的。参数是一个列表,而不是一个字符串。 – 2010-02-26 18:16:12
好吧,它本身并没有错,因为它会创建一个字符串表示,但是如果您要将它作为列表反正 – 2010-03-01 11:29:26