Results of a command - Math 101

Table of Contents

Results of a command - Math 101
OPERANDS
OPERATORS
MATH FUNCTIONS
TYPE CONVERSIONS
Example

Results of a command - Math 101

The Tcl command for doing math type operations is expr. The following discussion of the expr command is extracted and adapted from the expr man page. Many commands use expr behind the scenes in order to evaluate test expressions, such as if, while and for loops, discussed in later sections. All of the advice given here for expr also holds for these other commands.

expr takes all of its arguments ("2 + 2" for example) and evaluates the result as a Tcl "expression" (rather than a normal command), and returns the value. The operators permitted in Tcl expressions include all the standard math functions, logical operators, bitwise operators, as well as math functions like rand(), sqrt(), cosh() and so on. Expressions almost always yield numeric results (integer or floating-point values).

Performance tip: enclosing the arguments to expr in curly braces will result in faster code. So do expr {$i * 10} instead of simply expr $i * 10

WARNING: You should always use braces when evaluating expressions that may contain user input, to avoid possible security breaches. The expr command performs its own round of substitutions on variables and commands, so you should use braces to prevent the Tcl interpreter doing this as well (leading to double substitution). To illustrate the danger, consider this interactive session:


% set userinput {[puts DANGER!]}
[puts DANGER!]
% expr $userinput == 1
DANGER!
0
% expr {$userinput == 1}
0

In the first example, the code contained in the user-supplied input is evaluated, whereas in the second the braces prevent this potential danger. As a general rule, always surround expressions with braces, whether using expr directly or some other command that takes an expression (such as if or while).