Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/tcl8.5.2/doc/expr.n @ 25

Last change on this file since 25 was 25, checked in by landauf, 16 years ago

added tcl to libs

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