如何安全地处理可选参数
我正在编写一个过程来在输出文件中创建标头。
目前它需要一个可选参数,这是标题的可能注释。
我最终将其编码为单个可选参数
proc dump_header { test description {comment = ""}}
,但想知道如何使用 args 实现相同的效果
proc dump_header { test description args }
很容易检查 args 是否为单个空白参数($args ==“”),但无法应对好吧,如果传递多个参数 - 而且我无论如何都需要否定检查。
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 = ""}}
but would like to know how I can achieve the same using args
proc dump_header { test description 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的过程定义不正确(您会收到错误消息
参数说明符“comment =”“”中的字段太多
)。应该是:如果您想使用
args
,您可以检查它的llength
:您可能还想在列表中传递名称-值对:
有些人更喜欢组合
args
和名称-值对(a la Tk)Your proc definition is incorrect (you'd get the error message
too many fields in argument specifier "comment = """
). Should be:If you want to use
args
, you could examine thellength
of it:You might also want to pass name-value pairs in a list:
Some prefer a combination of
args
and name-value pairs (a la Tk)我使用 tcllib 的 cmdline 库来进行选项解析。
这是 cmdline 文档中的示例:
因此,在您的情况下,您只需使用
args
代替上面示例中的argv
即可。I use tcllib's cmdline library to do option parsing.
This is the example from cmdline documentation:
So, in your case, you'd just use
args
in place ofargv
in the above example.应该明确指出,
args
是 Tcl 中的一个特殊词,当在参数列表末尾使用时,它包含所有剩余参数的列表。如果没有给出 args,则不会产生错误(与任何其他变量名称不同,它被视为必需参数)。我一直在寻找一种具有类似于 python 的 kwargs (可选键值对参数)的功能的方法,并且效果很好的方法是(类似于 Glenn 的最后一个示例):
调用:
并且可以这样 潜在的缺点(正如我目前已经实现的那样)是,如果用户传递未经批准的键值选项,则不会出现错误。
It should be mentioned explicitly that
args
is a special word in Tcl that, when used at the end of the argument list, contains a list of all the remaining arguments. If noargs
are given, then no error is produced (unlike any other variable name, which would be considered a required argument).I was looking for a way to have functionality similar to python's
kwargs
(optional key-value pair arguments), and something that works nicely is (similar to Glenn's last example):And can be called like:
A potential downside (as I've currently implemented it) is that if a user passes a non-approved key-value option, there is no error.