In TCL, How to make a variable use the value of another variable


I need to use the value of a variable inside another variable.

This is what I tried..

set cmd_ts "foo bar"
set confCmds {
puts "confCmds = $confCmds"

But instead of getting

confCmds = 
    foo bar

I am getting:

confCmds =

P.S. I tried the following to no avail

  1. $cmd_ts
  2. "$cmd_ts"
  3. {$cmd_ts}
  4. \$cmd_ts

Best Solution

(almost) nothing will work as long as you use curly braces. The best suggestion is to use the list command:

set confCmds [list command1 command2 $cmd_ts]

I say (almost) because you can use subst to do variable substitution on confCmds, but that's not really what you want and that is fraught with peril. What you want is a list of words, one or more of which may be defined by a variable. That is precisely what the above solution gives you.

If you want, you can spread the commands on more than one line by using the backslash:

set confCmds [list \
    command1 \
    command2 \
    $cmd_ts \

This solution assumes that what you want is a tcl list. This may or may not be what you want, it all depends on how you treat this data downstream.

In a comment you wrote that what you really want is a string of newline-separated items, in which case you can just use double quotes, for example:

set confCmds "

That will give you a string with multiple lines separated by newlines. Be careful of trying to treat this as a list of commands (ie: don't do 'foreach foo $confCmds') because it can fail depending on what is in $cmd_ts.

Related Question