tags:

views:

128

answers:

4

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

try

puts [set ${t}_top]
Jackson
+1  A: 

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.

RHSeeger
+5  A: 

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.

Bryan Oakley
A: 

The syntax

puts [expr $${t}_top]

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

bta
That's really bad style, as it has potential execution hazards. (Consider the devious variable name “`::argc+[file delete -force /]+$`”.) The standard syntax of Jackson's answer is safe, and Bryan's answer is what *really* ought to be done.
Donal Fellows
I agree, and I would argue that *any* method of dynamically creating variable names is bad style. I was trying to correct the OP's syntax more than their style. I assumed that devious examples like yours would never be an issue, since `t` should always be under your control (I can't imagine a case where it would make sense to build a variable name based on user/external input).
bta