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