tags:

views:

258

answers:

3

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

This is what I tried..

set cmd_ts "foo bar"
set confCmds {
    command1
    command2
    $cmd_ts
}
puts "confCmds = $confCmds"

But instead of getting

confCmds = 
    command1
    command2
    foo bar

I am getting:

confCmds =
    command1
    command2
    $cmd_ts

P.S. I tried the following to no avail

  1. $cmd_ts
  2. "$cmd_ts"
  3. {$cmd_ts}
  4. \$cmd_ts
+5  A: 

(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 "
    command1
    command2
    $cmd_ts
"

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.

Bryan Oakley
Actually I want command1, command2 and $cmd_ts to be separated by a new line, but using list or concat I get them together as a space delimited string. Any idea how to achieve that as I am facing a rough time tackling \n :P
Aman Jain
You can use double quotes instead of curly braces in your original example. As long as you not later treating this data as a Tcl list you'll be fine. Another option is to convert the tcl list you just created into a string of newline separated items with [join $confCmds \n]
Bryan Oakley
+2  A: 

Bryan's answer is good, apart from a typo I can't fix with my rep. (the list in the first command should be ended with a square bracket).

If you want to do anything useful with the commands, you probably want them as a list, but if you just want them separated by a new line do this at the end:

set confCmds [join $confCmds "\n"]
Michael Hinds
thanks for pointing out the typo. I've fixed it.
Bryan Oakley
+1  A: 

If you must have the list defined as you have it, you can also use the subst command, which will perform the substitution that the curly braces are preventing:

subst $confCmds
ramanman