Debian Codegraph @

doc/expr.n

raw
1 '\"
2 '\" Copyright (c) 1993 The Regents of the University of California.
3 '\" Copyright (c) 1994-2000 Sun Microsystems, Inc.
4 '\" Copyright (c) 2005 Kevin B. Kenny <[email protected]>. All rights reserved
5 '\"
6 '\" See the file "license.terms" for information on usage and redistribution
7 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
8 '\"
9 .TH expr n 8.5 Tcl "Tcl Built-In Commands"
10 .so man.macros
11 .BS
12 '\" Note: do not modify the .SH NAME line immediately below!
13 .SH NAME
14 expr \- Evaluate an expression
15 .SH SYNOPSIS
16 \fBexpr \fIarg \fR?\fIarg arg ...\fR?
17 .BE
18 .SH DESCRIPTION
19 .PP
20 Concatenates \fIarg\fRs (adding separator spaces between them),
21 evaluates the result as a Tcl expression, and returns the value.
22 The operators permitted in Tcl expressions include a subset of
23 the operators permitted in C expressions. For those operators
24 common to both Tcl and C, Tcl applies the same meaning and precedence
25 as the corresponding C operators.
26 Expressions almost always yield numeric results
27 (integer or floating-point values).
28 For example, the expression
29 .PP
30 .CS
31 \fBexpr\fR 8.2 + 6
32 .CE
33 .PP
34 evaluates to 14.2.
35 Tcl expressions differ from C expressions in the way that
36 operands are specified. Also, Tcl expressions support
37 non-numeric operands and string comparisons, as well as some
38 additional operators not found in C.
39 .SS OPERANDS
40 .PP
41 A Tcl expression consists of a combination of operands, operators,
42 parentheses and commas.
43 White space may be used between the operands and operators and
44 parentheses (or commas); it is ignored by the expression's instructions.
45 Where possible, operands are interpreted as integer values.
46 Integer values may be specified in decimal (the normal case), in binary
47 (if the first two characters of the operand are \fB0b\fR), in octal
48 (if the first two characters of the operand are \fB0o\fR), or in hexadecimal
49 (if the first two characters of the operand are \fB0x\fR). For
50 compatibility with older Tcl releases, an octal integer value is also
51 indicated simply when the first character of the operand is \fB0\fR,
52 whether or not the second character is also \fBo\fR.
53 If an operand does not have one of the integer formats given
54 above, then it is treated as a floating-point number if that is
55 possible. Floating-point numbers may be specified in any of several
56 common formats making use of the decimal digits, the decimal point \fB.\fR,
57 the characters \fBe\fR or \fBE\fR indicating scientific notation, and
58 the sign characters \fB+\fR or \fB\-\fR. For example, all of the
59 following are valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16.
60 Also recognized as floating point values are the strings \fBInf\fR
61 and \fBNaN\fR making use of any case for each character.
62 If no numeric interpretation is possible (note that all literal
63 operands that are not numeric or boolean must be quoted with either
64 braces or with double quotes), then an operand is left as a string
65 (and only a limited set of operators may be applied to it).
66 .PP
67 Operands may be specified in any of the following ways:
68 .IP [1]
69 As a numeric value, either integer or floating-point.
70 .IP [2]
71 As a boolean value, using any form understood by \fBstring is\fR
72 \fBboolean\fR.
73 .IP [3]
74 As a Tcl variable, using standard \fB$\fR notation.
75 The variable's value will be used as the operand.
76 .IP [4]
77 As a string enclosed in double-quotes.
78 The expression parser will perform backslash, variable, and
79 command substitutions on the information between the quotes,
80 and use the resulting value as the operand
81 .IP [5]
82 As a string enclosed in braces.
83 The characters between the open brace and matching close brace
84 will be used as the operand without any substitutions.
85 .IP [6]
86 As a Tcl command enclosed in brackets.
87 The command will be executed and its result will be used as
88 the operand.
89 .IP [7]
90 As a mathematical function whose arguments have any of the above
91 forms for operands, such as \fBsin($x)\fR. See \fBMATH FUNCTIONS\fR below for
92 a discussion of how mathematical functions are handled.
93 .PP
94 Where the above substitutions occur (e.g. inside quoted strings), they
95 are performed by the expression's instructions.
96 However, the command parser may already have performed one round of
97 substitution before the expression processor was called.
98 As discussed below, it is usually best to enclose expressions
99 in braces to prevent the command parser from performing substitutions
100 on the contents.
101 .PP
102 For some examples of simple expressions, suppose the variable
103 \fBa\fR has the value 3 and
104 the variable \fBb\fR has the value 6.
105 Then the command on the left side of each of the lines below
106 will produce the value on the right side of the line:
107 .PP
108 .CS
109 .ta 9c
110 \fBexpr\fR {3.1 + $a} \fI6.1\fR
111 \fBexpr\fR {2 + "$a.$b"} \fI5.6\fR
112 \fBexpr\fR {4*[llength "6 2"]} \fI8\fR
113 \fBexpr\fR {{word one} < "word $a"} \fI0\fR
114 .CE
115 .SS OPERATORS
116 .PP
117 The valid operators (most of which are also available as commands in
118 the \fBtcl::mathop\fR namespace; see the \fBmathop\fR(n) manual page
119 for details) are listed below, grouped in decreasing order of precedence:
120 .TP 20
121 \fB\-\0\0+\0\0~\0\0!\fR
122 .
123 Unary minus, unary plus, bit-wise NOT, logical NOT. None of these operators
124 may be applied to string operands, and bit-wise NOT may be
125 applied only to integers.
126 .TP 20
127 \fB**\fR
128 .
129 Exponentiation. Valid for any numeric operands. The maximum exponent value
130 that Tcl can handle if the first number is an integer > 1 is 268435455.
131 .TP 20
132 \fB*\0\0/\0\0%\fR
133 .
134 Multiply, divide, remainder. None of these operators may be
135 applied to string operands, and remainder may be applied only
136 to integers.
137 The remainder will always have the same sign as the divisor and
138 an absolute value smaller than the absolute value of the divisor.
139 .RS
140 .PP
141 When applied to integers, the division and remainder operators can be
142 considered to partition the number line into a sequence of equal-sized
143 adjacent non-overlapping pieces where each piece is the size of the divisor;
144 the division result identifies which piece the divisor lay within, and the
145 remainder result identifies where within that piece the divisor lay. A
146 consequence of this is that the result of
147 .QW "-57 \fB/\fR 10"
148 is always -6, and the result of
149 .QW "-57 \fB%\fR 10"
150 is always 3.
151 .RE
152 .TP 20
153 \fB+\0\0\-\fR
154 .
155 Add and subtract. Valid for any numeric operands.
156 .TP 20
157 \fB<<\0\0>>\fR
158 .
159 Left and right shift. Valid for integer operands only.
160 A right shift always propagates the sign bit.
161 .TP 20
162 \fB<\0\0>\0\0<=\0\0>=\fR
163 .
164 Boolean less, greater, less than or equal, and greater than or equal.
165 Each operator produces 1 if the condition is true, 0 otherwise.
166 These operators may be applied to strings as well as numeric operands,
167 in which case string comparison is used.
168 .TP 20
169 \fB==\0\0!=\fR
170 .
171 Boolean equal and not equal. Each operator produces a zero/one result.
172 Valid for all operand types.
173 .TP 20
174 \fBeq\0\0ne\fR
175 .
176 Boolean string equal and string not equal. Each operator produces a
177 zero/one result. The operand types are interpreted only as strings.
178 .TP 20
179 \fBin\0\0ni\fR
180 .
181 List containment and negated list containment. Each operator produces
182 a zero/one result and treats its first argument as a string and its
183 second argument as a Tcl list. The \fBin\fR operator indicates
184 whether the first argument is a member of the second argument list;
185 the \fBni\fR operator inverts the sense of the result.
186 .TP 20
187 \fB&\fR
188 .
189 Bit-wise AND. Valid for integer operands only.
190 .TP 20
191 \fB^\fR
192 .
193 Bit-wise exclusive OR. Valid for integer operands only.
194 .TP 20
195 \fB|\fR
196 .
197 Bit-wise OR. Valid for integer operands only.
198 .TP 20
199 \fB&&\fR
200 .
201 Logical AND. Produces a 1 result if both operands are non-zero,
202 0 otherwise.
203 Valid for boolean and numeric (integers or floating-point) operands only.
204 This operator evaluates lazily; it only evaluates its second operand if it
205 must in order to determine its result.
206 .TP 20
207 \fB||\fR
208 .
209 Logical OR. Produces a 0 result if both operands are zero, 1 otherwise.
210 Valid for boolean and numeric (integers or floating-point) operands only.
211 This operator evaluates lazily; it only evaluates its second operand if it
212 must in order to determine its result.
213 .TP 20
214 \fIx \fB?\fI y \fB:\fI z\fR
215 .
216 If-then-else, as in C. If \fIx\fR
217 evaluates to non-zero, then the result is the value of \fIy\fR.
218 Otherwise the result is the value of \fIz\fR.
219 The \fIx\fR operand must have a boolean or numeric value.
220 This operator evaluates lazily; it evaluates only one of \fIy\fR or \fIz\fR.
221 .PP
222 See the C manual for more details on the results
223 produced by each operator.
224 The exponentiation operator promotes types like the multiply and
225 divide operators, and produces a result that is the same as the output
226 of the \fBpow\fR function (after any type conversions.)
227 All of the binary operators but exponentiation group left-to-right
228 within the same precedence level; exponentiation groups right-to-left. For example, the command
229 .PP
230 .PP
231 .CS
232 \fBexpr\fR {4*2 < 7}
233 .CE
234 .PP
235 returns 0, while
236 .PP
237 .CS
238 \fBexpr\fR {2**3**2}
239 .CE
240 .PP
241 returns 512.
242 .PP
243 The \fB&&\fR, \fB||\fR, and \fB?:\fR operators have
244 .QW "lazy evaluation" ,
245 just as in C, which means that operands are not evaluated if they are
246 not needed to determine the outcome. For example, in the command
247 .PP
248 .CS
249 \fBexpr\fR {$v?[a]:[b]}
250 .CE
251 .PP
252 only one of
253 .QW \fB[a]\fR
254 or
255 .QW \fB[b]\fR
256 will actually be evaluated,
257 depending on the value of \fB$v\fR. Note, however, that this is
258 only true if the entire expression is enclosed in braces; otherwise
259 the Tcl parser will evaluate both
260 .QW \fB[a]\fR
261 and
262 .QW \fB[b]\fR
263 before invoking the \fBexpr\fR command.
264 .SS "MATH FUNCTIONS"
265 .PP
266 When the expression parser encounters a mathematical function
267 such as \fBsin($x)\fR, it replaces it with a call to an ordinary
268 Tcl command in the \fBtcl::mathfunc\fR namespace. The processing
269 of an expression such as:
270 .PP
271 .CS
272 \fBexpr\fR {sin($x+$y)}
273 .CE
274 .PP
275 is the same in every way as the processing of:
276 .PP
277 .CS
278 \fBexpr\fR {[tcl::mathfunc::sin [\fBexpr\fR {$x+$y}]]}
279 .CE
280 .PP
281 which in turn is the same as the processing of:
282 .PP
283 .CS
284 tcl::mathfunc::sin [\fBexpr\fR {$x+$y}]
285 .CE
286 .PP
287 The executor will search for \fBtcl::mathfunc::sin\fR using the usual
288 rules for resolving functions in namespaces. Either
289 \fB::tcl::mathfunc::sin\fR or \fB[namespace
290 current]::tcl::mathfunc::sin\fR will satisfy the request, and others
291 may as well (depending on the current \fBnamespace path\fR setting).
292 .PP
293 Some mathematical functions have several arguments, separated by commas like in C. Thus:
294 .PP
295 .CS
296 \fBexpr\fR {hypot($x,$y)}
297 .CE
298 .PP
299 ends up as
300 .PP
301 .CS
302 tcl::mathfunc::hypot $x $y
303 .CE
304 .PP
305 See the \fBmathfunc\fR(n) manual page for the math functions that are
306 available by default.
307 .SS "TYPES, OVERFLOW, AND PRECISION"
308 .PP
309 All internal computations involving integers are done calling on the
310 LibTomMath multiple precision integer library as required so that all
311 integer calculations are performed exactly. Note that in Tcl releases
312 prior to 8.5, integer calculations were performed with one of the C types
313 \fIlong int\fR or \fITcl_WideInt\fR, causing implicit range truncation
314 in those calculations where values overflowed the range of those types.
315 Any code that relied on these implicit truncations will need to explicitly
316 add \fBint()\fR or \fBwide()\fR function calls to expressions at the points
317 where such truncation is required to take place.
318 .PP
319 All internal computations involving floating-point are
320 done with the C type \fIdouble\fR.
321 When converting a string to floating-point, exponent overflow is
322 detected and results in the \fIdouble\fR value of \fBInf\fR or
323 \fB\-Inf\fR as appropriate. Floating-point overflow and underflow
324 are detected to the degree supported by the hardware, which is generally
325 pretty reliable.
326 .PP
327 Conversion among internal representations for integer, floating-point,
328 and string operands is done automatically as needed.
329 For arithmetic computations, integers are used until some
330 floating-point number is introduced, after which floating-point is used.
331 For example,
332 .PP
333 .CS
334 \fBexpr\fR {5 / 4}
335 .CE
336 .PP
337 returns 1, while
338 .PP
339 .CS
340 \fBexpr\fR {5 / 4.0}
341 \fBexpr\fR {5 / ( [string length "abcd"] + 0.0 )}
342 .CE
343 .PP
344 both return 1.25.
345 Floating-point values are always returned with a
346 .QW \fB.\fR
347 or an
348 .QW \fBe\fR
349 so that they will not look like integer values. For example,
350 .PP
351 .CS
352 \fBexpr\fR {20.0/5.0}
353 .CE
354 .PP
355 returns \fB4.0\fR, not \fB4\fR.
356 .SS "STRING OPERATIONS"
357 .PP
358 String values may be used as operands of the comparison operators,
359 although the expression evaluator tries to do comparisons as integer
360 or floating-point when it can,
361 i.e., when all arguments to the operator allow numeric interpretations,
362 except in the case of the \fBeq\fR and \fBne\fR operators.
363 If one of the operands of a comparison is a string and the other
364 has a numeric value, a canonical string representation of the numeric
365 operand value is generated to compare with the string operand.
366 Canonical string representation for integer values is a decimal string
367 format. Canonical string representation for floating-point values
368 is that produced by the \fB%g\fR format specifier of Tcl's
369 \fBformat\fR command. For example, the commands
370 .PP
371 .CS
372 \fBexpr\fR {"0x03" > "2"}
373 \fBexpr\fR {"0y" > "0x12"}
374 .CE
375 .PP
376 both return 1. The first comparison is done using integer
377 comparison, and the second is done using string comparison.
378 Because of Tcl's tendency to treat values as numbers whenever
379 possible, it is not generally a good idea to use operators like \fB==\fR
380 when you really want string comparison and the values of the
381 operands could be arbitrary; it is better in these cases to use
382 the \fBeq\fR or \fBne\fR operators, or the \fBstring\fR command instead.
383 .SH "PERFORMANCE CONSIDERATIONS"
384 .PP
385 Enclose expressions in braces for the best speed and the smallest
386 storage requirements.
387 This allows the Tcl bytecode compiler to generate the best code.
388 .PP
389 As mentioned above, expressions are substituted twice:
390 once by the Tcl parser and once by the \fBexpr\fR command.
391 For example, the commands
392 .PP
393 .CS
394 set a 3
395 set b {$a + 2}
396 \fBexpr\fR $b*4
397 .CE
398 .PP
399 return 11, not a multiple of 4.
400 This is because the Tcl parser will first substitute
401 .QW "\fB$a + 2\fR"
402 for the variable \fBb\fR,
403 then the \fBexpr\fR command will evaluate the expression
404 .QW "\fB$a + 2*4\fR" .
405 .PP
406 Most expressions do not require a second round of substitutions.
407 Either they are enclosed in braces or, if not,
408 their variable and command substitutions yield numbers or strings
409 that do not themselves require substitutions.
410 However, because a few unbraced expressions
411 need two rounds of substitutions,
412 the bytecode compiler must emit
413 additional instructions to handle this situation.
414 The most expensive code is required for
415 unbraced expressions that contain command substitutions.
416 These expressions must be implemented by generating new code
417 each time the expression is executed.
418 .PP
419 If it is necessary to include a non-constant expression string within the
420 wider context of an otherwise-constant expression, the most efficient
421 technique is to put the varying part inside a recursive \fBexpr\fR, as this at
422 least allows for the compilation of the outer part, though it does mean that
423 the varying part must itself be evaluated as a separate expression. Thus, in
424 this example the result is 20 and the outer expression benefits from fully
425 cached bytecode compilation.
426 .PP
427 .CS
428 set a 3
429 set b {$a + 2}
430 \fBexpr\fR {[\fBexpr\fR $b] * 4}
431 .CE
432 .PP
433 When the expression is unbraced to allow the substitution of a function or
434 operator, consider using the commands documented in the \fBmathfunc\fR(n) or
435 \fBmathop\fR(n) manual pages directly instead.
436 .SH EXAMPLES
437 .PP
438 Define a procedure that computes an
439 .QW interesting
440 mathematical function:
441 .PP
442 .CS
443 proc tcl::mathfunc::calc {x y} {
444 \fBexpr\fR { ($x**2 - $y**2) / exp($x**2 + $y**2) }
445 }
446 .CE
447 .PP
448 Convert polar coordinates into cartesian coordinates:
449 .PP
450 .CS
451 # convert from ($radius,$angle)
452 set x [\fBexpr\fR { $radius * cos($angle) }]
453 set y [\fBexpr\fR { $radius * sin($angle) }]
454 .CE
455 .PP
456 Convert cartesian coordinates into polar coordinates:
457 .PP
458 .CS
459 # convert from ($x,$y)
460 set radius [\fBexpr\fR { hypot($y, $x) }]
461 set angle [\fBexpr\fR { atan2($y, $x) }]
462 .CE
463 .PP
464 Print a message describing the relationship of two string values to
465 each other:
466 .PP
467 .CS
468 puts "a and b are [\fBexpr\fR {$a eq $b ? {equal} : {different}}]"
469 .CE
470 .PP
471 Set a variable to whether an environment variable is both defined at
472 all and also set to a true boolean value:
473 .PP
474 .CS
475 set isTrue [\fBexpr\fR {
476 [info exists ::env(SOME_ENV_VAR)] &&
477 [string is true -strict $::env(SOME_ENV_VAR)]
478 }]
479 .CE
480 .PP
481 Generate a random integer in the range 0..99 inclusive:
482 .PP
483 .CS
484 set randNum [\fBexpr\fR { int(100 * rand()) }]
485 .CE
486 .SH "SEE ALSO"
487 array(n), for(n), if(n), mathfunc(n), mathop(n), namespace(n), proc(n),
488 string(n), Tcl(n), while(n)
489 .SH KEYWORDS
490 arithmetic, boolean, compare, expression, fuzzy comparison
491 .SH COPYRIGHT
492 .nf
493 Copyright \(co 1993 The Regents of the University of California.
494 Copyright \(co 1994-2000 Sun Microsystems Incorporated.
495 Copyright \(co 2005 Kevin B. Kenny <[email protected]>. All rights reserved.
496 .fi
497 '\" Local Variables:
498 '\" mode: nroff
499 '\" fill-column: 78
500 '\" End: