Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

tcl

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.

like image 931
Jeff C Avatar asked Dec 10 '22 18:12

Jeff C


1 Answers

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.

like image 167
Bryan Oakley Avatar answered Jan 22 '23 17:01

Bryan Oakley