1.4 Variables and Substitutions
Tcl allows you to store values in variables and use those values in commands. For example, consider the following script, which you could enter in either tclsh or wish:
set a 44 ⇒ 44 expr $a*4 ⇒ 176
The first command assigns the value 44 to the variable a and returns the variable's value. In the second command, the $ causes Tcl to perform variable substitution: the Tcl interpreter replaces the dollar sign and the variable name following it with the value of the variable, so that the actual argument received by expr is 44*4. Variables need not be declared in Tcl; they are created automatically when set. Variable values can always be represented as strings but may be maintained in a native binary format. Strings may contain binary data and may be of any length. Of course, in this example an error occurs in expr if the value of a doesn't make sense as an integer or real number.
Tcl also provides command substitution, which allows you to use the result of one command in an argument to another command:
set a 44 set b [expr $a*4] ⇒ 176
Square brackets invoke command substitution: everything inside the brackets is evaluated as a separate Tcl script, and the result of that script is substituted into the word in place of the bracketed command. In this example the second argument of the second set command is 176.
The final form of substitution in Tcl is backslash substitution, which either adds special meaning to a normal character or takes it away from a special character, as in the following examples:
set x \$a set newline \n
The first command sets the variable x to the string $a (the characters \$ are replaced with a dollar sign and no variable substitution occurs). The second command sets the variable newline to hold a string consisting of the newline character (the characters \n are replaced with a newline character).