XPS-Q8
Tcl Manual
put opening curly braces on the line after a
while
or an
if
statement, you must
escape the newline with a backslash:
while
{$i < $x} \
{
set
product ...
}
Always group expressions and command bodies with curly
braces.
Curly braces around the boolean expression are crucial because they delay variable
substitution until the
while
command implementation tests the expression. The
following is an example that will result in is an infinite loop:
set
i 1;
while
$i<=
10
{
incr
i}
The loop will run indefinitely.
*
The reason is that the Tcl interpreter will substitute for
$i
before
while
is called, so
while
gets a constant expression
1<=10
that
will always be true. You can avoid these kinds of errors by adopting a consistent coding
convention that groups expressions with curly braces:
set
i 1;
while
{$i<=
10
} {
incr
i}
The
incr
command is used to increment the value of the loop variable
i
. This is a
handy command that saves us from the longer command:
set
i [
expr
$i + 1]
The
incr
command can take an additional argument, a positive or negative integer by
which to change the value of the variable. In this form, it is possible to eliminate the
loop variable
i
and just modify the parameter
x
. The loop body can be written like
this:
while
{$x > 1} {
set
product [
expr
$product * $x]
incr
x -1
}
Example 1–14 shows another factorial, this time using a recursive definition. A
recursive function is one that calls itself to complete its work. Each recursive call
decrements
x
by one, until the value of
x
is equal to one, and then the recursion stops.
Example 1–14: A recursive definition of factorial.
proc
Factorial {x} {
if
{$x <=
1
} {
return
1
}
else
{
return
[
expr
$x * [Factorial [
expr
$x -
1
]]]
}
}
2.2.9
More about Variables
The
set
command will return the value of a variable only if it is passed in single
argument. It treats that argument as a variable name and returns the current value of the
variable. The dollar-sign syntax used to get the value of a variable is really just an easy
way to use the
set
command. Example 1–15 shows a clever way to circumvent this
restriction by putting the name of one variable into another variable:
Example 1–15: Using
set
to return a variable value.
set
var {the value of var}
⇒
the value of var
set
name var
EDH0307En1041 — 10/17
9