list 将列表传递给 Tcl 过程

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1596711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 01:24:20  来源:igfitidea点击:

Passing list to Tcl procedure

listargumentstcl

提问by Juan

What is the canonical way to pass a list to a Tcl procedure?

将列表传递给 Tcl 过程的规范方法是什么?

I'd really like it if I could get it so that a list is automatically expanded into a variable number of arguments.

如果我能得到它,我真的很喜欢它,以便将列表自动扩展为可变数量的参数。

So that something like:

所以像这样:

set a {b c}
myprocedure option1 option2 $a

and

myprocedure option1 option2 b c

are equivalent.

是等价的。

I am sure I saw this before, but I can't find it anywhere online. Any help (and code) to make both cases equivalent would be appreciated.

我确定我以前看过这个,但我在网上找不到它。任何使这两种情况等效的帮助(和代码)将不胜感激。

Is this considered a standard Tcl convention. Or am I even barking up the wrong tree?

这是否被认为是标准的 Tcl 约定。或者我什至在错误的树上吠叫?

回答by RHSeeger

It depends on the version of Tcl you're using, but: For 8.5:

这取决于您使用的 Tcl 版本,但是:对于 8.5:

set mylist {a b c}
myprocedure option1 option2 {*}$mylist

For 8.4 and below:

对于 8.4 及以下版本:

set mylist {a b c}
eval myprocedure option1 option2 $mylist
# or, if option1 and 2 are variables
eval myprocedure [list $option1] [list $option2] $mylist
# or, as Bryan prefers
eval myprocedure $option1 $option2 $mylist

回答by glenn Hymanman

To expand on RHSeeger's answer, you would code myprocedure with the special argsargument like this:

要扩展 RHSeeger 的答案,您可以使用如下特殊args参数对 myprocedure 进行编码:

proc myprocedure {opt1 opt2 args} {
    puts "opt1=$opt1"
    puts "opt2=$opt2"
    puts "args=[list $args]" ;# just use [list] for output formatting
    puts "args has [llength $args] elements"
}

回答by dougcosine

It might be useful to note that passing your command to catchwill also solve this problem:

需要注意的是,将命令传递给catch也可以解决这个问题:

set a {b c}
if [catch "myprocedure option1 option2 $a"] {
    # handle errors
}

This should probably only be used if you want to handle errors in myprocedure at this point in your code so that you don't have to worry about rethrowing any errors that get caught.

这可能只在您想在代码中处理 myprocedure 中的错误时使用,这样您就不必担心重新抛出任何被捕获的错误。