XPS-Q8
Tcl Manual
2.2.2
Variables
The
set
command is used to assign a value to a variable. It requires two arguments:
The first is the name of the variable, and the second is the value. Variable names can be
any length, and case
is
recognized
. In fact, you can use any character in a variable
name.
NOTE
It is not necessary to declare Tcl variables before you use them.
The interpreter will create the variable when it is assigned a value.
The value of a variable is obtained later with the dollar-sign syntax, as illustrated in
Example 1–2.
Example 1–2: Tcl variables.
set
var
5
⇒
5
set
b $var
⇒
5
The second
set
command assigns to variable
b
the value of variable
var
.
The use of the dollar sign is our first example of substitution. You might guess that the
second
set
command substitutes the value of
var
for
$var
to obtain a new
command.
set
b
5
The actual implementation of substitution is more efficient, which is important when the
value is large.
2.2.3
Command Substitution
The second form of substitution is
command substitution
. A nested command is
delimited by square brackets,
[ ]
. The Tcl interpreter takes everything between the
brackets and evaluates it as a command. Rewriting the outer command by replacing the
square brackets and everything between them with the result of the nested command.
This is similar to the use of backquotes in other shells, except that it has the additional
advantage of supporting arbitrary nesting of commands.
Example 1–3: Command substitution.
set
len [
string
length
foobar]
⇒
6
In Example 1–3, the nested command is:
string length foobar
This command returns the length of the string
foobar
. The nested command runs first.
Then, command substitution causes the outer command to be rewritten as if it were:
set
len
6
If there are several cases of command substitution within a single command, the
interpreter processes them from left to right. As each right bracket is encountered, the
command it delimits is evaluated. This results in a sensible ordering in which nested
commands are evaluated first so that their result can be passed as arguments to the outer
command.
EDH0307En1041 — 10/17
3