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 {
    command1
    command2
    $cmd_ts
}
puts "confCmds = $confCmds"

But instead of getting

confCmds = 
    command1
    command2
    foo bar

I get:

confCmds =
    command1
    command2
    $cmd_ts

PS I tried the following to no avail

  • $ cmd_ts
  • "$ cmd_ts"
  • {$ cmd_ts}
  • \ $ cmd_ts
+3
source share
3 answers

(almost) nothing will work as long as you use curly braces. It is best to use a list command:

set confCmds [list command1 command2 $cmd_ts]

I say (almost) because you can use subst to replace variables in confCmds, but this is not exactly what you want, and it is fraught with danger. What you want is a list of words, one or more of which can be defined by a variable. This is exactly what gives you the indicated solution.

, , :

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

, tcl. , , , .

, , , , :

set confCmds "
    command1
    command2
    $cmd_ts
"

, . , (.. "foreach foo $confCmds" ), , $cmd_ts.

+9

, , . ( ).

- , , , , , , , :

set confCmds [join $confCmds "\n"]
+4

If you must have a list defined as you have, you can also use the subst command, which will perform the replacement, which is prevented by curly braces:

subst $confCmds
+2
source

Source: https://habr.com/ru/post/1708162/


All Articles