TCL Variables and Variable Substitution
Variables in Tcl, as in most other languages, can be thought of as boxes in which various kinds of data can be stored. These boxes, or variables, are given names, which are then used to access the values stored in them.
Unlike C, Tcl does not require that variables be declared before they are used. Tcl variables are simply created when they are first assigned
values, using the set command. Although they do not have to be deleted, Tcl variables can be deleted
using the unset command.
The value stored in a variable can be accessed by prefacing the name of the variable with a dollar sign ("$"). This is known as variable substitution, and is illustrated in the examples below.
Tcl is an example of a "weakly typed" language. This simply means that almost any type of data can be stored in any variable. For example, the same variable can be used to store a number, a date, a string, or even another Tcl script.
Example 1.1:
set foo "john" puts "Hi my name is $foo"
Output: Hi my name is john
Example 1.1 illustrates the use of variable substitution. The value "john" is assigned to the variable "foo", whose value
is then substituted for "$foo". Note that variable substitution can occur within a string. The puts
command (described in a later section) is used to display the string.
Example 1.2:
set month 2 set day 3 set year 97 set date "$month:$day:$year" puts $date
Output: 2:3:97
Here variable substitution is used in several places: The values of the variables "month", "day", and "year"
are substituted in the set command that assigns the value of the "date" variable, and the value
of the "date" variable is then substituted in the line that displays the output.
Example 1.3:
set foo "puts hi" eval $foo
Output: hi
In this example, the variable "foo" holds another (small) Tcl script that simply prints the word "hi". The value of the
variable "foo" is substituted into an eval command, which causes it to be evaluated by the Tcl interpreter (the eval command will be described
in greater detail in a later section).