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