gpt4 book ai didi

tcl - 如何安全处理可选参数

转载 作者:行者123 更新时间:2023-12-04 13:12:29 25 4
gpt4 key购买 nike

我正在编写一个在输出文件中创建 header 的proc。

当前,它需要一个可选参数,该参数可能是标题的注释。

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

proc dump_header { test description {comment = ""}}

但想知道我如何使用args达到同样的效果
proc dump_header { test description args }

检查args是否为单个空白参数($ args ==“”)非常容易,但是如果传递多个参数则无法很好地应对-我仍然需要否定检查。

最佳答案

您的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和名称/值对组合在一起(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

关于tcl - 如何安全处理可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2341441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com