tcl: how to use the value of a variable to create a new variable

﹥>﹥吖頭↗ 提交于 2021-01-02 19:17:08

问题


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.


回答1:


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:

set t SNS
set ${t}_top  [commands that return value]
...
puts [set ${t}_top]

Do this:

set t SNS
set top($t) [commands that return value]
...
puts $top($t)

Most people agree that the latter example is much more readable.




回答2:


try

puts [set ${t}_top]



回答3:


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

set var1 1
set var2 var1
set var3 $$var2

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):

set var3 [set $var2]

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.




回答4:


The syntax

puts [expr $${t}_top]

works as well, and avoids using the 'set' operation so a syntax error shouldn't overwrite your data.



来源:https://stackoverflow.com/questions/1613240/tcl-how-to-use-the-value-of-a-variable-to-create-a-new-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!