XPS-Q8
Tcl Manual
2.2.9.3
Using info exists to check whether a variable exists
The existence of a variable can be tested with the
info
exists
command. For
example, because
incr
requires that a variable exist, you might have to test for the
existence of the variable first.
Example 1–17: Using
info
to determine if a variable exists.
if {![
info
exists
foobar]} {
set
foobar 0
} else {
incr
foobar
}
2.2.10
More about Math Expressions
This section describes a few of the finer points about mathematics in Tcl scripts. In Tcl
7.6 and earlier versions math is not very efficient due to required conversions between
strings and numbers. The
expr
command must convert arguments from strings to
numbers. It then does computations with double precision floating point values. The
result is formatted into a string that have, by default, 12 significant digits. This number
can be changed by setting the
tcl_precision
variable to the number of significant
digits desired. Typically seventeen digits of precision are enough to insure that no
information is lost when converting back and forth between a string and an IEEE double
precision number:
Example 1–18: Controlling precision with
tcl_precision
.
expr
1
/
3
⇒
0
expr
1
/
3.0
⇒
0.333333333333
set
tcl_precision
17
⇒
17
expr
1
/
3.0
# The trailing 1 is the IEEE rounding digit
⇒
0.33333333333333331
In Tcl 8.0 and later versions, the overhead of conversions is eliminated in most cases by
the built-in compiler. Nevertheless, Tcl was not designed to support math-intensive
applications. There is support for string comparisons by
expr
, so you can test string
values with
if
statements. You must use quotes so that
expr
knows that you are
doing a string comparison:
if
{$answer ==
"yes"
} { ... }
However, the
string
compare
and
string
equal
commands are more
reliable because
expr
may do conversions on strings that look like numbers.
Expressions can include variable and command substitutions and still be grouped with
curly braces. This is because an argument to
expr
is subject to two rounds of
substitution: one by the Tcl interpreter, and a second by
expr
itself. Ordinarily this is
not a problem because math values do not contain the characters that are special to the
Tcl interpreter. The second round of substitutions is needed to support commands like
while
and
if
that use the expression evaluator internally.
Grouping expressions can make them run more efficiently.
You should always group expressions in curly braces and let
expr
take care of
command and variable substitutions. Otherwise, your values may suffer extra
conversions from numbers to strings and back to numbers. Not only is this process
slow, but the conversions can loose precision in certain circumstances. For example,
suppose
x
is computed from a math function:
EDH0307En1041 — 10/17
11