2 expr - Evaluate an expression
9 Concatenates args (adding separator spaces between them), evaluates the
10 result as a Tcl expression, and returns the value. The operators per-
11 mitted in Tcl expressions are a subset of the operators permitted in C
12 expressions, and they have the same meaning and precedence as the cor-
13 responding C operators. Expressions almost always yield numeric
14 results (integer or floating-point values). For example, the expres-
17 evaluates to 14.2. Tcl expressions differ from C expressions in the
18 way that operands are specified. Also, Tcl expressions support non-
19 numeric operands and string comparisons.
22 A Tcl expression consists of a combination of operands, operators, and
23 parentheses. White space may be used between the operands and opera-
24 tors and parentheses; it is ignored by the expression's instructions.
25 Where possible, operands are interpreted as integer values. Integer
26 values may be specified in decimal (the normal case), in octal (if the
27 first character of the operand is 0), or in hexadecimal (if the first
28 two characters of the operand are 0x). If an operand does not have one
29 of the integer formats given above, then it is treated as a floating-
30 point number if that is possible. Floating-point numbers may be speci-
31 fied in any of the ways accepted by an ANSI-compliant C compiler
32 (except that the f, F, l, and L suffixes will not be permitted in most
33 installations). For example, all of the following are valid floating-
34 point numbers: 2.1, 3., 6e4, 7.91e+16. If no numeric interpretation
35 is possible (note that all literal operands that are not numeric or
36 boolean must be quoted with either braces or with double quotes), then
37 an operand is left as a string (and only a limited set of operators may
40 On 32-bit systems, integer values MAX_INT (0x7FFFFFFF) and MIN_INT
41 (-0x80000000) will be represented as 32-bit values, and integer values
42 outside that range will be represented as 64-bit values (if that is
45 Operands may be specified in any of the following ways:
47 [1] As a numeric value, either integer or floating-point.
49 [2] As a boolean value, using any form understood by string is
52 [3] As a Tcl variable, using standard $ notation. The variable's
53 value will be used as the operand.
55 [4] As a string enclosed in double-quotes. The expression parser
56 will perform backslash, variable, and command substitutions on
57 the information between the quotes, and use the resulting value
60 [5] As a string enclosed in braces. The characters between the open
61 brace and matching close brace will be used as the operand with-
62 out any substitutions.
64 [6] As a Tcl command enclosed in brackets. The command will be exe-
65 cuted and its result will be used as the operand.
67 [7] As a mathematical function whose arguments have any of the above
68 forms for operands, such as sin($x). See below for a list of
71 Where the above substitutions occur (e.g. inside quoted strings), they
72 are performed by the expression's instructions. However, the command
73 parser may already have performed one round of substitution before the
74 expression processor was called. As discussed below, it is usually
75 best to enclose expressions in braces to prevent the command parser
76 from performing substitutions on the contents.
78 For some examples of simple expressions, suppose the variable a has the
79 value 3 and the variable b has the value 6. Then the command on the
80 left side of each of the lines below will produce the value on the
81 right side of the line:
84 expr 4*[llength "6 2"] 8
85 expr {{word one} < "word $a"}0
88 The valid operators are listed below, grouped in decreasing order of
91 - + ~ ! Unary minus, unary plus, bit-wise NOT, logical NOT.
92 None of these operators may be applied to string
93 operands, and bit-wise NOT may be applied only to
96 * / % Multiply, divide, remainder. None of these opera-
97 tors may be applied to string operands, and remain-
98 der may be applied only to integers. The remainder
99 will always have the same sign as the divisor and
100 an absolute value smaller than the divisor.
102 + - Add and subtract. Valid for any numeric operands.
104 << >> Left and right shift. Valid for integer operands
105 only. A right shift always propagates the sign
108 < > <= >= Boolean less, greater, less than or equal, and
109 greater than or equal. Each operator produces 1 if
110 the condition is true, 0 otherwise. These opera-
111 tors may be applied to strings as well as numeric
112 operands, in which case string comparison is used.
114 == != Boolean equal and not equal. Each operator pro-
115 duces a zero/one result. Valid for all operand
118 eq ne Boolean string equal and string not equal. Each
119 operator produces a zero/one result. The operand
120 types are interpreted only as strings.
122 & Bit-wise AND. Valid for integer operands only.
124 ^ Bit-wise exclusive OR. Valid for integer operands
127 | Bit-wise OR. Valid for integer operands only.
129 && Logical AND. Produces a 1 result if both operands
130 are non-zero, 0 otherwise. Valid for boolean and
131 numeric (integers or floating-point) operands only.
133 || Logical OR. Produces a 0 result if both operands
134 are zero, 1 otherwise. Valid for boolean and
135 numeric (integers or floating-point) operands only.
137 x?y:z If-then-else, as in C. If x evaluates to non-zero,
138 then the result is the value of y. Otherwise the
139 result is the value of z. The x operand must have
140 a boolean or numeric value.
142 See the C manual for more details on the results produced by each oper-
143 ator. All of the binary operators group left-to-right within the same
144 precedence level. For example, the command
148 The &&, ||, and ?: operators have ``lazy evaluation'', just as in C,
149 which means that operands are not evaluated if they are not needed to
150 determine the outcome. For example, in the command
151 expr {$v ? [a] : [b]}
152 only one of [a] or [b] will actually be evaluated, depending on the
153 value of $v. Note, however, that this is only true if the entire
154 expression is enclosed in braces; otherwise the Tcl parser will evalu-
155 ate both [a] and [b] before invoking the expr command.
158 Tcl supports the following mathematical functions in expressions, all
159 of which work solely with floating-point numbers unless otherwise
163 acos double log10 srand
166 atan2 fmod round wide
173 Returns the absolute value of arg. Arg may be either integer or
174 floating-point, and the result is returned in the same form.
177 Returns the arc cosine of arg, in the range [0,pi] radians. Arg
178 should be in the range [-1,1].
181 Returns the arc sine of arg, in the range [-pi/2,pi/2] radians.
182 Arg should be in the range [-1,1].
185 Returns the arc tangent of arg, in the range [-pi/2,pi/2] radi-
189 Returns the arc tangent of y/x, in the range [-pi,pi] radians.
190 x and y cannot both be 0. If x is greater than 0, this is
191 equivalent to atan(y/x).
194 Returns the smallest integral floating-point value (i.e. with a
195 zero fractional part) not less than arg.
198 Returns the cosine of arg, measured in radians.
201 Returns the hyperbolic cosine of arg. If the result would cause
202 an overflow, an error is returned.
205 If arg is a floating-point value, returns arg, otherwise con-
206 verts arg to floating-point and returns the converted value.
209 Returns the exponential of arg, defined as e**arg. If the
210 result would cause an overflow, an error is returned.
213 Returns the largest integral floating-point value (i.e. with a
214 zero fractional part) not greater than arg.
217 Returns the floating-point remainder of the division of x by y.
218 If y is 0, an error is returned.
221 Computes the length of the hypotenuse of a right-angled triangle
225 If arg is an integer value of the same width as the machine
226 word, returns arg, otherwise converts arg to an integer (of the
227 same size as a machine word, i.e. 32-bits on 32-bit systems, and
228 64-bits on 64-bit systems) by truncation and returns the con-
232 Returns the natural logarithm of arg. Arg must be a positive
236 Returns the base 10 logarithm of arg. Arg must be a positive
240 Computes the value of x raised to the power y. If x is nega-
241 tive, y must be an integer value.
243 rand() Returns a pseudo-random floating-point value in the range (0,1).
244 The generator algorithm is a simple linear congruential genera-
245 tor that is not cryptographically secure. Each result from rand
246 completely determines all future results from subsequent calls
247 to rand, so rand should not be used to generate a sequence of
248 secrets, such as one-time passwords. The seed of the generator
249 is initialized from the internal clock of the machine or may be
250 set with the srand function.
253 If arg is an integer value, returns arg, otherwise converts arg
254 to integer by rounding and returns the converted value.
257 Returns the sine of arg, measured in radians.
260 Returns the hyperbolic sine of arg. If the result would cause
261 an overflow, an error is returned.
264 Returns the square root of arg. Arg must be non-negative.
267 The arg, which must be an integer, is used to reset the seed for
268 the random number generator of rand. Returns the first random
269 number (see rand()) from that seed. Each interpreter has its
273 Returns the tangent of arg, measured in radians.
276 Returns the hyperbolic tangent of arg.
279 Converts arg to an integer value at least 64-bits wide (by sign-
280 extension if arg is a 32-bit number) if it is not one already.
282 In addition to these predefined functions, applications may define
283 additional functions using Tcl_CreateMathFunc().
285 TYPES, OVERFLOW, AND PRECISION
286 All internal computations involving integers are done with the C type
287 long, and all internal computations involving floating-point are done
288 with the C type double. When converting a string to floating-point,
289 exponent overflow is detected and results in a Tcl error. For conver-
290 sion to integer from string, detection of overflow depends on the
291 behavior of some routines in the local C library, so it should be
292 regarded as unreliable. In any case, integer overflow and underflow
293 are generally not detected reliably for intermediate results. Float-
294 ing-point overflow and underflow are detected to the degree supported
295 by the hardware, which is generally pretty reliable.
297 Conversion among internal representations for integer, floating-point,
298 and string operands is done automatically as needed. For arithmetic
299 computations, integers are used until some floating-point number is
300 introduced, after which floating-point is used. For example,
304 expr 5 / ( [string length "abcd"] + 0.0 )
305 both return 1.25. Floating-point values are always returned with a
306 ``.'' or an e so that they will not look like integer values. For
312 String values may be used as operands of the comparison operators,
313 although the expression evaluator tries to do comparisons as integer or
314 floating-point when it can, except in the case of the eq and ne opera-
315 tors. If one of the operands of a comparison is a string and the other
316 has a numeric value, the numeric operand is converted back to a string
317 using the C sprintf format specifier %d for integers and %g for float-
318 ing-point values. For example, the commands
321 both return 1. The first comparison is done using integer comparison,
322 and the second is done using string comparison after the second operand
323 is converted to the string 18. Because of Tcl's tendency to treat val-
324 ues as numbers whenever possible, it isn't generally a good idea to use
325 operators like == when you really want string comparison and the values
326 of the operands could be arbitrary; it's better in these cases to use
327 the eq or ne operators, or the string command instead.
330 PERFORMANCE CONSIDERATIONS
331 Enclose expressions in braces for the best speed and the smallest stor-
332 age requirements. This allows the Tcl bytecode compiler to generate
335 As mentioned above, expressions are substituted twice: once by the Tcl
336 parser and once by the expr command. For example, the commands
340 return 11, not a multiple of 4. This is because the Tcl parser will
341 first substitute $a + 2 for the variable b, then the expr command will
342 evaluate the expression $a + 2*4.
344 Most expressions do not require a second round of substitutions.
345 Either they are enclosed in braces or, if not, their variable and com-
346 mand substitutions yield numbers or strings that don't themselves
347 require substitutions. However, because a few unbraced expressions
348 need two rounds of substitutions, the bytecode compiler must emit addi-
349 tional instructions to handle this situation. The most expensive code
350 is required for unbraced expressions that contain command substitu-
351 tions. These expressions must be implemented by generating new code
352 each time the expression is executed.
355 Define a procedure that computes an "interesting" mathematical func-
358 expr { ($x*$x - $y*$y) / exp($x*$x + $y*$y) }
361 Convert polar coordinates into cartesian coordinates:
362 # convert from ($radius,$angle)
363 set x [expr { $radius * cos($angle) }]
364 set y [expr { $radius * sin($angle) }]
366 Convert cartesian coordinates into polar coordinates:
367 # convert from ($x,$y)
368 set radius [expr { hypot($y, $x) }]
369 set angle [expr { atan2($y, $x) }]
371 Print a message describing the relationship of two string values to
373 puts "a and b are [expr {$a eq $b ? {equal} : {different}}]"
375 Set a variable to whether an environment variable is both defined at
376 all and also set to a true boolean value:
378 [info exists ::env(SOME_ENV_VAR)] &&
379 [string is true -strict $::env(SOME_ENV_VAR)]
382 Generate a random integer in the range 0..99 inclusive:
383 set randNum [expr { int(100 * rand()) }]
387 array(n), for(n), if(n), string(n), Tcl(n), while(n)