Tcl v8.4 中让 proc 返回数组的最佳方法是什么?
如果我有一个过程需要将数组返回给其调用者,那么最好的方法是什么?
由于无法 $ 数组变量,我下面的代码在 Tcl 中不起作用:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
$foo
}
tcl> set foo [mine]
Error: can't read "foo": variable is array
或者这也不起作用:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
array get foo
}
tcl> set foo [mine]
tcl> puts $foo(blue)
Error: can't read "foo(blue)": variable isn't array
这给我带来了可能效率低下的问题:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
array get foo
}
tcl> array set foo [mine]
2
或者晦涩难懂的:
proc mine {varName} {
upvar $varName localVar
array set localVar { red 1 blue 2 green 3 }
}
tcl>unset foo
tcl>mine foo
tcl>puts $foo(blue)
2
是否有更好的方法来做到这一点,或者如果没有,哪个最有效率?
If I have a proc that needs to return an array to its caller, what is the best way to do this?
I following code does not work in Tcl due to inability to $ an array variable:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
$foo
}
tcl> set foo [mine]
Error: can't read "foo": variable is array
Alternatively this doesn't work either:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
array get foo
}
tcl> set foo [mine]
tcl> puts $foo(blue)
Error: can't read "foo(blue)": variable isn't array
This leaves me with the probably inefficient:
proc mine {} {
array set foo { red 1 blue 2 green 3 }
array get foo
}
tcl> array set foo [mine]
2
Or the obscure:
proc mine {varName} {
upvar $varName localVar
array set localVar { red 1 blue 2 green 3 }
}
tcl>unset foo
tcl>mine foo
tcl>puts $foo(blue)
2
Is there a better way to do this, or if not, which is the most efficient?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想你已经回答了你自己的问题。简而言之,您不能返回数组。您在问题中解释了一些选项:
1)您可以返回数组值,并将其转换回调用者中的数组
2)您可以在过程中使用 upvar ,以便调用者传入一个数组的名称,然后您可以修改该数组。
如果您使用 tcl 8.5,您可能需要考虑改用字典。字典是第一类对象,可以传递、从过程返回等。
I think you've answered your own question. Simply put, you cannot return an array. There are options, which you explained in your question:
1) you can return the array value, and convert it back to an array in the caller
2) you can use upvar in your procedure so that the caller passes in the name of an array which you can then modify.
If you are using tcl 8.5 you might want to consider switching to using a dict. Dicts are first class objects that can be passed around, returned from procedures, etc.
如果您需要使用数组,我的偏好是您显示的 [array get/set] 组合:
也就是说,如果您使用 Tcl 8.5 或更高版本,您可以考虑使用字典。它们通常会更快、更干净。
My preference, if you need to use arrays, is the [array get/set] combo you showed:
That being said, if you're using Tcl 8.5 or later, you can consider using dicts. They're generally going to be faster and cleaner.