Node:Expressions, Next:, Previous:Commands to Do with Variables, Up:Commands


Expressions are constructed from operands and operators and can then be evaluated. The most general expression evaluator in Tcl is the expr command:

expr arg ?arg arg ... arg?

which evaluates its arguments as an expression and returns the value of the evaluation.

A simple example expression is

expr 2 * 2

which when executed returns the value 4.

There are different classes of operators: arithmetic, relational, logical, bitwise, and choice. Here are some example expressions involving various operators:

arithmetic $x * 2
relational $x > 2
logical ($x == $y) || ($x == $z)
bitwise 8 & 2
choice ($a == 1) ? $x : $y

Basically the operators follow the syntax and meaning of their ANSI C counterparts.

Expressions to the expr command can be contained in curly brackets in which case the usual substitutions are not done before the expr command is evaluated, but the command does its own round of substitutions. So evaluating a script such as:

set a 1
expr { ($a==1) : "yes" ? "no" }

will evaluate to yes.

Tcl also has a whole host of math functions that can be used in expressions. Their evaluation is again the same as that for their ANSI C counterparts. For example:

expr { 2*log($x) }

will return 2 times the natural log of the value of variable x.