tcl:如何使用变量的值创建新变量
这是我正在尝试做的一个例子。
set t SNS
set ${t}_top [commands that return value]
想要获取存储在 ${t}_top 的信息
puts “${t}_top”
SNS_top (really want the data stored there?)
以为是: ${{$t}_top} ,也许那是 perl 但 {} 内的 {} 不起作用。
here is an example of what I'm trying to do.
set t SNS
set ${t}_top [commands that return value]
Want to get the info stored at ${t}_top
puts “${t}_top”
SNS_top (really want the data stored there?)
Thought it was : ${{$t}_top} , maybe that was perl but {} inside the {} do not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Tcl 真正有趣的事情之一是您可以动态创建变量名称,就像您在发布的问题中所做的那样。然而,这使得编写起来很棘手,并且使代码变得比必要的更难理解。
与其试图弄清楚如何执行与 ${{$t}_top} 相同的操作,可以说最好完全避免这个问题。您可以通过使用关联数组来做到这一点。
例如,不要这样做:
这样做:
大多数人都认为后一个示例更具可读性。
One of the really interesting things about Tcl is that you can create variable names dynamically, as you are doing in the question you posted. However, this makes it tricky to write and makes your code harder than necessary to understand.
Instead of trying to figure out how to do the equivalent of ${{$t}_top}, it's arguably better to avoid the problem altogether. You can do that by using an associative array.
For example, instead of this:
Do this:
Most people agree that the latter example is much more readable.
尝试
try
Tcl 中的每一行代码通常只运行一次替换阶段(其中变量、命令等被替换)。因此,类似的事情
不会以 var3 等于 1 结束,因为替换器将用“名为 '$var2' 的变量的值(字面意思)”替换“$$var2”并停止。
你需要它要么以另一种方式处理事情,要么强制进行另一轮替代。另一种方法通常是避免需要第二轮替换(如 Jackson 所示):
这里,在替换期间 $var2 被“var1”替换...然后 [set var1] 返回 1...然后 var3被设置为值“1”......并且你很好。
Each line of code in Tcl is run through the substitution phase (in which variables, commands, etc are substituted) only once... generally. As such, something like
won't wind up with var3 equaling 1, since the substitutor will replace "$$var2" with "the value of the variable named '$var2' (literally)" and stop.
What you need it to either go about things another way or to force another round of substitution. The other way is generally to avoid needing a second round of substitution (as shown by Jackson):
Here, the $var2 is replaced, during substitution, by "var1"... then [set var1] returns 1... then var3 gets set to the value of "1"... and you're good.
该语法
也有效,并避免使用“设置”操作,因此语法错误不应覆盖您的数据。
The syntax
works as well, and avoids using the 'set' operation so a syntax error shouldn't overwrite your data.