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-
27 numeric operands and string comparisons, as well as some additional
28 operators 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
110 * / % Multiply, divide, remainder. None of these opera‐
111 tors may be applied to string operands, and remain‐
112 der may be applied only to integers. The remainder
113 will always have the same sign as the divisor and
114 an absolute value smaller than the absolute value
115 of the divisor.
116
117 When applied to integers, the division and remain‐
118 der operators can be considered to partition the
119 number line into a sequence of equal-sized adjacent
120 non-overlapping pieces where each piece is the size
121 of the divisor; the division result identifies
122 which piece the divisor lay within, and the remain‐
123 der result identifies where within that piece the
124 divisor lay. A consequence of this is that the
125 result of “-57 / 10” is always -6, and the result
126 of “-57 % 10” is always 3.
127
128 + - Add and subtract. Valid for any numeric operands.
129
130 << >> Left and right shift. Valid for integer operands
131 only. A right shift always propagates the sign
132 bit.
133
134 < > <= >= Boolean less, greater, less than or equal, and
135 greater than or equal. Each operator produces 1 if
136 the condition is true, 0 otherwise. These opera‐
137 tors may be applied to strings as well as numeric
138 operands, in which case string comparison is used.
139
140 == != Boolean equal and not equal. Each operator pro‐
141 duces a zero/one result. Valid for all operand
142 types.
143
144 eq ne Boolean string equal and string not equal. Each
145 operator produces a zero/one result. The operand
146 types are interpreted only as strings.
147
148 in ni List containment and negated list containment.
149 Each operator produces a zero/one result and treats
150 its first argument as a string and its second argu‐
151 ment as a Tcl list. The in operator indicates
152 whether the first argument is a member of the sec‐
153 ond argument list; the ni operator inverts the
154 sense of the result.
155
156 & Bit-wise AND. Valid for integer operands only.
157
158 ^ Bit-wise exclusive OR. Valid for integer operands
159 only.
160
161 | Bit-wise OR. Valid for integer operands only.
162
163 && Logical AND. Produces a 1 result if both operands
164 are non-zero, 0 otherwise. Valid for boolean and
165 numeric (integers or floating-point) operands only.
166
167 || Logical OR. Produces a 0 result if both operands
168 are zero, 1 otherwise. Valid for boolean and
169 numeric (integers or floating-point) operands only.
170
171 x?y:z If-then-else, as in C. If x evaluates to non-zero,
172 then the result is the value of y. Otherwise the
173 result is the value of z. The x operand must have
174 a boolean or numeric value.
175
176 See the C manual for more details on the results produced by each oper‐
177 ator. The exponentiation operator promotes types like the multiply and
178 divide operators, and produces a result that is the same as the output
179 of the pow function (after any type conversions.) All of the binary
180 operators but exponentiation group left-to-right within the same prece‐
181 dence level; exponentiation groups right-to-left. For example, the
182 command
183
184 expr {4*2 < 7}
185
186 returns 0, while
187
188 expr {2**3**2}
189
190 returns 512.
191
192 The &&, ||, and ?: operators have “lazy evaluation”, just as in C,
193 which means that operands are not evaluated if they are not needed to
194 determine the outcome. For example, in the command
195
196 expr {$v ? [a] : [b]}
197
198 only one of “[a]” or “[b]” will actually be evaluated, depending on the
199 value of $v. Note, however, that this is only true if the entire
200 expression is enclosed in braces; otherwise the Tcl parser will evalu‐
201 ate both “[a]” and “[b]” before invoking the expr command.
202
203 MATH FUNCTIONS
204 When the expression parser encounters a mathematical function such as
205 sin($x), it replaces it with a call to an ordinary Tcl function in the
206 tcl::mathfunc namespace. The processing of an expression such as:
207
208 expr {sin($x+$y)}
209
210 is the same in every way as the processing of:
211
212 expr {[tcl::mathfunc::sin [expr {$x+$y}]]}
213
214 which in turn is the same as the processing of:
215
216 tcl::mathfunc::sin [expr {$x+$y}]
217
218 The executor will search for tcl::mathfunc::sin using the usual rules
219 for resolving functions in namespaces. Either ::tcl::mathfunc::sin or
220 [namespace current]::tcl::mathfunc::sin will satisfy the request, and
221 others may as well (depending on the current namespace path setting).
222
223 Some mathematical functions have several arguments, separated by commas
224 like in C. Thus:
225
226 expr {hypot($x,$y)}
227
228 ends up as
229
230 tcl::mathfunc::hypot $x $y
231
232 See the mathfunc(n) manual page for the math functions that are avail‐
233 able by default.
234
235 TYPES, OVERFLOW, AND PRECISION
236 All internal computations involving integers are done calling on the
237 LibTomMath multiple precision integer library as required so that all
238 integer calculations are performed exactly. Note that in Tcl releases
239 prior to 8.5, integer calculations were performed with one of the C
240 types long int or Tcl_WideInt, causing implicit range truncation in
241 those calculations where values overflowed the range of those types.
242 Any code that relied on these implicit truncations will need to explic‐
243 itly add int() or wide() function calls to expressions at the points
244 where such truncation is required to take place.
245
246 All internal computations involving floating-point are done with the C
247 type double. When converting a string to floating-point, exponent
248 overflow is detected and results in the double value of Inf or -Inf as
249 appropriate. Floating-point overflow and underflow are detected to the
250 degree supported by the hardware, which is generally pretty reliable.
251
252 Conversion among internal representations for integer, floating-point,
253 and string operands is done automatically as needed. For arithmetic
254 computations, integers are used until some floating-point number is
255 introduced, after which floating-point is used. For example,
256
257 expr {5 / 4}
258
259 returns 1, while
260
261 expr {5 / 4.0}
262 expr {5 / ( [string length "abcd"] + 0.0 )}
263
264 both return 1.25. Floating-point values are always returned with a “.”
265 or an “e” so that they will not look like integer values. For example,
266
267 expr {20.0/5.0}
268
269 returns 4.0, not 4.
270
271 STRING OPERATIONS
272 String values may be used as operands of the comparison operators,
273 although the expression evaluator tries to do comparisons as integer or
274 floating-point when it can, i.e., when all arguments to the operator
275 allow numeric interpretations, except in the case of the eq and ne
276 operators. If one of the operands of a comparison is a string and the
277 other has a numeric value, a canonical string representation of the
278 numeric operand value is generated to compare with the string operand.
279 Canonical string representation for integer values is a decimal string
280 format. Canonical string representation for floating-point values is
281 that produced by the %g format specifier of Tcl's format command. For
282 example, the commands
283
284 expr {"0x03" > "2"}
285 expr {"0y" > "0x12"}
286
287 both return 1. The first comparison is done using integer comparison,
288 and the second is done using string comparison. Because of Tcl's ten‐
289 dency to treat values as numbers whenever possible, it is not generally
290 a good idea to use operators like == when you really want string com‐
291 parison and the values of the operands could be arbitrary; it is bet‐
292 ter in these cases to use the eq or ne operators, or the string command
293 instead.
294
296 Enclose expressions in braces for the best speed and the smallest stor‐
297 age requirements. This allows the Tcl bytecode compiler to generate
298 the best code.
299
300 As mentioned above, expressions are substituted twice: once by the Tcl
301 parser and once by the expr command. For example, the commands
302
303 set a 3
304 set b {$a + 2}
305 expr $b*4
306
307 return 11, not a multiple of 4. This is because the Tcl parser will
308 first substitute $a + 2 for the variable b, then the expr command will
309 evaluate the expression $a + 2*4.
310
311 Most expressions do not require a second round of substitutions.
312 Either they are enclosed in braces or, if not, their variable and com‐
313 mand substitutions yield numbers or strings that do not themselves
314 require substitutions. However, because a few unbraced expressions
315 need two rounds of substitutions, the bytecode compiler must emit addi‐
316 tional instructions to handle this situation. The most expensive code
317 is required for unbraced expressions that contain command substitu‐
318 tions. These expressions must be implemented by generating new code
319 each time the expression is executed. When the expression is unbraced
320 to allow the substitution of a function or operator, consider using the
321 commands documented in the mathfunc(n) or mathop(n) manual pages
322 directly instead.
323
325 Define a procedure that computes an “interesting” mathematical func‐
326 tion:
327
328 proc tcl::mathfunc::calc {x y} {
329 expr { ($x**2 - $y**2) / exp($x**2 + $y**2) }
330 }
331
332 Convert polar coordinates into cartesian coordinates:
333
334 # convert from ($radius,$angle)
335 set x [expr { $radius * cos($angle) }]
336 set y [expr { $radius * sin($angle) }]
337
338 Convert cartesian coordinates into polar coordinates:
339
340 # convert from ($x,$y)
341 set radius [expr { hypot($y, $x) }]
342 set angle [expr { atan2($y, $x) }]
343
344 Print a message describing the relationship of two string values to
345 each other:
346
347 puts "a and b are [expr {$a eq $b ? {equal} : {different}}]"
348
349 Set a variable to whether an environment variable is both defined at
350 all and also set to a true boolean value:
351
352 set isTrue [expr {
353 [info exists ::env(SOME_ENV_VAR)] &&
354 [string is true -strict $::env(SOME_ENV_VAR)]
355 }]
356
357 Generate a random integer in the range 0..99 inclusive:
358
359 set randNum [expr { int(100 * rand()) }]
360
362 array(n), for(n), if(n), mathfunc(n), mathop(n), namespace(n), proc(n),
363 string(n), Tcl(n), while(n)
364
366 arithmetic, boolean, compare, expression, fuzzy comparison
367
369 Copyright (c) 1993 The Regents of the University of California.
370 Copyright (c) 1994-2000 Sun Microsystems Incorporated.
371 Copyright (c) 2005 by Kevin B. Kenny <kennykb@acm.org>. All rights reserved.
372
373
374
375Tcl 8.5 expr(n)