1expr(n) Tcl Built-In Commands expr(n)
2
3
4
5______________________________________________________________________________
6
8 expr - Evaluate an expression
9
11 expr arg ?arg arg ...?
12______________________________________________________________________________
13
15 Concatenates args (adding separator spaces between them), evaluates the
16 result as a Tcl expression, and returns the value. The operators per‐
17 mitted in Tcl expressions include a subset of the operators permitted
18 in C expressions. For those operators common to both Tcl and C, Tcl
19 applies the same meaning and precedence as the corresponding C opera‐
20 tors. Expressions almost always yield numeric results (integer or
21 floating-point values). For example, the expression
22
23 expr 8.2 + 6
24
25 evaluates to 14.2. Tcl expressions differ from C expressions in the
26 way that operands are specified. Also, Tcl expressions support non-nu‐
27 meric operands and string comparisons, as well as some additional oper‐
28 ators not found in C.
29
30 OPERANDS
31 A Tcl expression consists of a combination of operands, operators,
32 parentheses and commas. White space may be used between the operands
33 and operators and parentheses (or commas); it is ignored by the expres‐
34 sion's instructions. Where possible, operands are interpreted as inte‐
35 ger values. Integer values may be specified in decimal (the normal
36 case), in binary (if the first two characters of the operand are 0b),
37 in octal (if the first two characters of the operand are 0o), or in
38 hexadecimal (if the first two characters of the operand are 0x). For
39 compatibility with older Tcl releases, an octal integer value is also
40 indicated simply when the first character of the operand is 0, whether
41 or not the second character is also o. If an operand does not have one
42 of the integer formats given above, then it is treated as a floating-
43 point number if that is possible. Floating-point numbers may be speci‐
44 fied in any of several common formats making use of the decimal digits,
45 the decimal point ., the characters e or E indicating scientific nota‐
46 tion, and the sign characters + or -. For example, all of the follow‐
47 ing are valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16. Also
48 recognized as floating point values are the strings Inf and NaN making
49 use of any case for each character. If no numeric interpretation is
50 possible (note that all literal operands that are not numeric or bool‐
51 ean must be quoted with either braces or with double quotes), then an
52 operand is left as a string (and only a limited set of operators may be
53 applied to it).
54
55 Operands may be specified in any of the following ways:
56
57 [1] As a numeric value, either integer or floating-point.
58
59 [2] As a boolean value, using any form understood by string is bool‐
60 ean.
61
62 [3] As a Tcl variable, using standard $ notation. The variable's
63 value will be used as the operand.
64
65 [4] As a string enclosed in double-quotes. The expression parser
66 will perform backslash, variable, and command substitutions on
67 the information between the quotes, and use the resulting value
68 as the operand
69
70 [5] As a string enclosed in braces. The characters between the open
71 brace and matching close brace will be used as the operand with‐
72 out any substitutions.
73
74 [6] As a Tcl command enclosed in brackets. The command will be exe‐
75 cuted and its result will be used as the operand.
76
77 [7] As a mathematical function whose arguments have any of the above
78 forms for operands, such as sin($x). See MATH FUNCTIONS below
79 for a discussion of how mathematical functions are handled.
80
81 Where the above substitutions occur (e.g. inside quoted strings), they
82 are performed by the expression's instructions. However, the command
83 parser may already have performed one round of substitution before the
84 expression processor was called. As discussed below, it is usually
85 best to enclose expressions in braces to prevent the command parser
86 from performing substitutions on the contents.
87
88 For some examples of simple expressions, suppose the variable a has the
89 value 3 and the variable b has the value 6. Then the command on the
90 left side of each of the lines below will produce the value on the
91 right side of the line:
92
93 expr {3.1 + $a} 6.1
94 expr {2 + "$a.$b"} 5.6
95 expr {4*[llength "6 2"]} 8
96 expr {{word one} < "word $a"} 0
97
98 OPERATORS
99 The valid operators (most of which are also available as commands in
100 the tcl::mathop namespace; see the mathop(n) manual page for details)
101 are listed below, grouped in decreasing order of precedence:
102
103 - + ~ ! Unary minus, unary plus, bit-wise NOT, logical NOT.
104 None of these operators may be applied to string
105 operands, and bit-wise NOT may be applied only to
106 integers.
107
108 ** Exponentiation. Valid for any numeric operands.
109 The maximum exponent value that Tcl can handle if
110 the first number is an integer > 1 is 268435455.
111
112 * / % Multiply, divide, remainder. None of these opera‐
113 tors may be applied to string operands, and remain‐
114 der may be applied only to integers. The remainder
115 will always have the same sign as the divisor and
116 an absolute value smaller than the absolute value
117 of the divisor.
118
119 When applied to integers, the division and remain‐
120 der operators can be considered to partition the
121 number line into a sequence of equal-sized adjacent
122 non-overlapping pieces where each piece is the size
123 of the divisor; the division result identifies
124 which piece the divisor lay within, and the remain‐
125 der result identifies where within that piece the
126 divisor lay. A consequence of this is that the re‐
127 sult of “-57 / 10” is always -6, and the result of
128 “-57 % 10” is always 3.
129
130 + - Add and subtract. Valid for any numeric operands.
131
132 << >> Left and right shift. Valid for integer operands
133 only. A right shift always propagates the sign
134 bit.
135
136 < > <= >= Boolean less, greater, less than or equal, and
137 greater than or equal. Each operator produces 1 if
138 the condition is true, 0 otherwise. These opera‐
139 tors may be applied to strings as well as numeric
140 operands, in which case string comparison is used.
141
142 == != Boolean equal and not equal. Each operator pro‐
143 duces a zero/one result. Valid for all operand
144 types.
145
146 eq ne Boolean string equal and string not equal. Each
147 operator produces a zero/one result. The operand
148 types are interpreted only as strings.
149
150 in ni List containment and negated list containment.
151 Each operator produces a zero/one result and treats
152 its first argument as a string and its second argu‐
153 ment as a Tcl list. The in operator indicates
154 whether the first argument is a member of the sec‐
155 ond argument list; the ni operator inverts the
156 sense of the result.
157
158 & Bit-wise AND. Valid for integer operands only.
159
160 ^ Bit-wise exclusive OR. Valid for integer operands
161 only.
162
163 | Bit-wise OR. Valid for integer operands only.
164
165 && Logical AND. Produces a 1 result if both operands
166 are non-zero, 0 otherwise. Valid for boolean and
167 numeric (integers or floating-point) operands only.
168 This operator evaluates lazily; it only evaluates
169 its second operand if it must in order to determine
170 its result.
171
172 || Logical OR. Produces a 0 result if both operands
173 are zero, 1 otherwise. Valid for boolean and nu‐
174 meric (integers or floating-point) operands only.
175 This operator evaluates lazily; it only evaluates
176 its second operand if it must in order to determine
177 its result.
178
179 x ? y : z If-then-else, as in C. If x evaluates to non-zero,
180 then the result is the value of y. Otherwise the
181 result is the value of z. The x operand must have
182 a boolean or numeric value. This operator evalu‐
183 ates lazily; it evaluates only one of y or z.
184
185 See the C manual for more details on the results produced by each oper‐
186 ator. The exponentiation operator promotes types like the multiply and
187 divide operators, and produces a result that is the same as the output
188 of the pow function (after any type conversions.) All of the binary
189 operators but exponentiation group left-to-right within the same prece‐
190 dence level; exponentiation groups right-to-left. For example, the
191 command
192
193 expr {4*2 < 7}
194
195 returns 0, while
196
197 expr {2**3**2}
198
199 returns 512.
200
201 The &&, ||, and ?: operators have “lazy evaluation”, just as in C,
202 which means that operands are not evaluated if they are not needed to
203 determine the outcome. For example, in the command
204
205 expr {$v?[a]:[b]}
206
207 only one of “[a]” or “[b]” will actually be evaluated, depending on the
208 value of $v. Note, however, that this is only true if the entire ex‐
209 pression is enclosed in braces; otherwise the Tcl parser will evaluate
210 both “[a]” and “[b]” before invoking the expr command.
211
212 MATH FUNCTIONS
213 When the expression parser encounters a mathematical function such as
214 sin($x), it replaces it with a call to an ordinary Tcl command in the
215 tcl::mathfunc namespace. The processing of an expression such as:
216
217 expr {sin($x+$y)}
218
219 is the same in every way as the processing of:
220
221 expr {[tcl::mathfunc::sin [expr {$x+$y}]]}
222
223 which in turn is the same as the processing of:
224
225 tcl::mathfunc::sin [expr {$x+$y}]
226
227 The executor will search for tcl::mathfunc::sin using the usual rules
228 for resolving functions in namespaces. Either ::tcl::mathfunc::sin or
229 [namespace current]::tcl::mathfunc::sin will satisfy the request, and
230 others may as well (depending on the current namespace path setting).
231
232 Some mathematical functions have several arguments, separated by commas
233 like in C. Thus:
234
235 expr {hypot($x,$y)}
236
237 ends up as
238
239 tcl::mathfunc::hypot $x $y
240
241 See the mathfunc(n) manual page for the math functions that are avail‐
242 able by default.
243
244 TYPES, OVERFLOW, AND PRECISION
245 All internal computations involving integers are done calling on the
246 LibTomMath multiple precision integer library as required so that all
247 integer calculations are performed exactly. Note that in Tcl releases
248 prior to 8.5, integer calculations were performed with one of the C
249 types long int or Tcl_WideInt, causing implicit range truncation in
250 those calculations where values overflowed the range of those types.
251 Any code that relied on these implicit truncations will need to explic‐
252 itly add int() or wide() function calls to expressions at the points
253 where such truncation is required to take place.
254
255 All internal computations involving floating-point are done with the C
256 type double. When converting a string to floating-point, exponent
257 overflow is detected and results in the double value of Inf or -Inf as
258 appropriate. Floating-point overflow and underflow are detected to the
259 degree supported by the hardware, which is generally pretty reliable.
260
261 Conversion among internal representations for integer, floating-point,
262 and string operands is done automatically as needed. For arithmetic
263 computations, integers are used until some floating-point number is in‐
264 troduced, after which floating-point is used. For example,
265
266 expr {5 / 4}
267
268 returns 1, while
269
270 expr {5 / 4.0}
271 expr {5 / ( [string length "abcd"] + 0.0 )}
272
273 both return 1.25. Floating-point values are always returned with a “.”
274 or an “e” so that they will not look like integer values. For example,
275
276 expr {20.0/5.0}
277
278 returns 4.0, not 4.
279
280 STRING OPERATIONS
281 String values may be used as operands of the comparison operators, al‐
282 though the expression evaluator tries to do comparisons as integer or
283 floating-point when it can, i.e., when all arguments to the operator
284 allow numeric interpretations, except in the case of the eq and ne op‐
285 erators. If one of the operands of a comparison is a string and the
286 other has a numeric value, a canonical string representation of the nu‐
287 meric operand value is generated to compare with the string operand.
288 Canonical string representation for integer values is a decimal string
289 format. Canonical string representation for floating-point values is
290 that produced by the %g format specifier of Tcl's format command. For
291 example, the commands
292
293 expr {"0x03" > "2"}
294 expr {"0y" > "0x12"}
295
296 both return 1. The first comparison is done using integer comparison,
297 and the second is done using string comparison. Because of Tcl's ten‐
298 dency to treat values as numbers whenever possible, it is not generally
299 a good idea to use operators like == when you really want string com‐
300 parison and the values of the operands could be arbitrary; it is bet‐
301 ter in these cases to use the eq or ne operators, or the string command
302 instead.
303
305 Enclose expressions in braces for the best speed and the smallest stor‐
306 age requirements. This allows the Tcl bytecode compiler to generate
307 the best code.
308
309 As mentioned above, expressions are substituted twice: once by the Tcl
310 parser and once by the expr command. For example, the commands
311
312 set a 3
313 set b {$a + 2}
314 expr $b*4
315
316 return 11, not a multiple of 4. This is because the Tcl parser will
317 first substitute “$a + 2” for the variable b, then the expr command
318 will evaluate the expression “$a + 2*4”.
319
320 Most expressions do not require a second round of substitutions. Ei‐
321 ther they are enclosed in braces or, if not, their variable and command
322 substitutions yield numbers or strings that do not themselves require
323 substitutions. However, because a few unbraced expressions need two
324 rounds of substitutions, the bytecode compiler must emit additional in‐
325 structions to handle this situation. The most expensive code is re‐
326 quired for unbraced expressions that contain command substitutions.
327 These expressions must be implemented by generating new code each time
328 the expression is executed.
329
330 If it is necessary to include a non-constant expression string within
331 the wider context of an otherwise-constant expression, the most effi‐
332 cient technique is to put the varying part inside a recursive expr, as
333 this at least allows for the compilation of the outer part, though it
334 does mean that the varying part must itself be evaluated as a separate
335 expression. Thus, in this example the result is 20 and the outer ex‐
336 pression benefits from fully cached bytecode compilation.
337
338 set a 3
339 set b {$a + 2}
340 expr {[expr $b] * 4}
341
342 When the expression is unbraced to allow the substitution of a function
343 or operator, consider using the commands documented in the mathfunc(n)
344 or mathop(n) manual pages directly instead.
345
347 Define a procedure that computes an “interesting” mathematical func‐
348 tion:
349
350 proc tcl::mathfunc::calc {x y} {
351 expr { ($x**2 - $y**2) / exp($x**2 + $y**2) }
352 }
353
354 Convert polar coordinates into cartesian coordinates:
355
356 # convert from ($radius,$angle)
357 set x [expr { $radius * cos($angle) }]
358 set y [expr { $radius * sin($angle) }]
359
360 Convert cartesian coordinates into polar coordinates:
361
362 # convert from ($x,$y)
363 set radius [expr { hypot($y, $x) }]
364 set angle [expr { atan2($y, $x) }]
365
366 Print a message describing the relationship of two string values to
367 each other:
368
369 puts "a and b are [expr {$a eq $b ? {equal} : {different}}]"
370
371 Set a variable to whether an environment variable is both defined at
372 all and also set to a true boolean value:
373
374 set isTrue [expr {
375 [info exists ::env(SOME_ENV_VAR)] &&
376 [string is true -strict $::env(SOME_ENV_VAR)]
377 }]
378
379 Generate a random integer in the range 0..99 inclusive:
380
381 set randNum [expr { int(100 * rand()) }]
382
384 array(n), for(n), if(n), mathfunc(n), mathop(n), namespace(n), proc(n),
385 string(n), Tcl(n), while(n)
386
388 arithmetic, boolean, compare, expression, fuzzy comparison
389
391 Copyright © 1993 The Regents of the University of California.
392 Copyright © 1994-2000 Sun Microsystems Incorporated.
393 Copyright © 2005 Kevin B. Kenny <kennykb@acm.org>. All rights reserved.
394
395
396
397Tcl 8.5 expr(n)