Monday, November 17, 2008

Math Expressions

The Tcl interpreter itself does not evaluate math expressions. Tcl just does
grouping, substitutions and command invocations. The expr command is used to
parse and evaluate math expressions.
Example 1–4 Simple arithmetic.
expr 7.2 / 4
=> 1.8
The math syntax supported by expr is the same as the C expression syntax.
The expr command deals with integer, floating point, and boolean values. Logical
operations return either 0 (false) or 1 (true). Integer values are promoted to floating
point values as needed. Octal values are indicated by a leading zero (e.g., 033
is 27 decimal). Hexadecimal values are indicated by a leading 0x. Scientific notation
for floating point numbers is supported. A summary of the operator precedence
is given on page 20.
You can include variable references and nested commands in math expressions.
The following example uses expr to add the value of x to the length of the
string foobar. As a result of the innermost command substitution, the expr command
sees 6 + 7, and len gets the value 13:
Example 1–5 Nested commands.
set x 7
set len [expr [string length foobar] + $x]
=> 13
The expression evaluator supports a number of built-in math functions.
(For a complete listing, see page 21.) Example 1–6 computes the value of pi:
Example 1–6 Built-in math functions.
set pi [expr 2*asin(1.0)]
=> 3.1415926535897931
Backslash Substitution 7

No comments: