You are here: Surpac Concepts > Macros > TCL > TCL command substitution
GEOVIA Surpac

TCL Command Substitution

Just as variable substitution is used to substitute the value of a variable into a Tcl script, command substitution can be used to replace a Tcl command with the result it returns. Consider the following example:

Example 3.1:

    puts "I am [expr 10 * 2] years old, and my I.Q. is [expr 100 - 25]"
      

Output: I am 20 years old, and my I.Q. is 75

As this example shows, square brackets are used to achieve command substitution: The text between the square brackets is evaluated as a Tcl script, and its result is then substituted in its place. In this case, command substitution is used to place the results of two mathematical expressions into a string. Command substitution is often used in conjunction with variable substitution, as shown in Example 3.2:

Example 3.2:

    set my_height 6.0
    puts "If I was 2 inches taller, I would be [expr $my_height + (2.0 / 12.0)] feet tall"
      

Output: If I was 2 inches taller, I would be 6.16667 feet tall

In this example, the value of the variable "my_height" is substituted inside the angle brackets before the command is evaluated. This is a good illustration of Tcl's one-pass recursive parsing mechanism. When evaluating a statement, the Tcl interpreter, makes one pass over it, and in doing so makes all the necessary substitutions. After this is done, the interpreter then evaluates the resulting expression. If, during its pass over the expression, the interpreter encounters square brackets (indicating that command substitution is to be performed), it recursively parses the script inside the square brackets in the same manner.