您的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