1expr(n)                      Tcl Built-In Commands                     expr(n)
2
3
4
5______________________________________________________________________________
6

NAME

8       expr - Evaluate an expression
9

SYNOPSIS

11       expr arg ?arg arg ...?
12_________________________________________________________________
13

DESCRIPTION

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 divisor.
111
112       +  -                Add and subtract.  Valid for any numeric operands.
113
114       <<  >>              Left and right shift.  Valid for  integer  operands
115                           only.   A  right  shift  always propagates the sign
116                           bit.
117
118       <  >  <=  >=        Boolean less, greater,  less  than  or  equal,  and
119                           greater than or equal.  Each operator produces 1 if
120                           the condition is true, 0 otherwise.   These  opera‐
121                           tors  may  be applied to strings as well as numeric
122                           operands, in which case string comparison is used.
123
124       ==  !=              Boolean equal and not equal.   Each  operator  pro‐
125                           duces  a  zero/one  result.   Valid for all operand
126                           types.
127
128       eq  ne              Boolean string equal and string  not  equal.   Each
129                           operator  produces  a zero/one result.  The operand
130                           types are interpreted only as strings.
131
132       in  ni              List  containment  and  negated  list  containment. │
133                           Each operator produces a zero/one result and treats │
134                           its first argument as a string and its second argu‐ │
135                           ment  as  a  Tcl  list.   The in operator indicates │
136                           whether the first argument is a member of the  sec‐ │
137                           ond  argument  list;  the  ni  operator inverts the │
138                           sense of the result.
139
140       &                   Bit-wise AND.  Valid for integer operands only.
141
142       ^                   Bit-wise exclusive OR.  Valid for integer  operands
143                           only.
144
145       |                   Bit-wise OR.  Valid for integer operands only.
146
147       &&                  Logical  AND.  Produces a 1 result if both operands
148                           are non-zero, 0 otherwise.  Valid for  boolean  and
149                           numeric (integers or floating-point) operands only.
150
151       ||                  Logical  OR.   Produces a 0 result if both operands
152                           are zero,  1  otherwise.   Valid  for  boolean  and
153                           numeric (integers or floating-point) operands only.
154
155       x?y:z               If-then-else, as in C.  If x evaluates to non-zero,
156                           then the result is the value of y.   Otherwise  the
157                           result  is the value of z.  The x operand must have
158                           a boolean or numeric value.
159
160       See the C manual for more details on the results produced by each oper‐
161       ator.  The exponentiation operator promotes types like the multiply and │
162       divide operators, and produces a result that is the same as the  output │
163       of  the  pow  function (after any type conversions.)  All of the binary
164       operators group left-to-right within the same  precedence  level.   For
165       example, the command
166              expr {4*2 < 7}
167       returns 0.
168
169       The  &&,  ||,  and  ?:  operators have “lazy evaluation”, just as in C,
170       which means that operands are not evaluated if they are not  needed  to
171       determine the outcome.  For example, in the command
172              expr {$v ? [a] : [b]}
173       only one of “[a]” or “[b]” will actually be evaluated, depending on the
174       value of $v.  Note, however, that this  is  only  true  if  the  entire
175       expression is enclosed in braces;  otherwise the Tcl parser will evalu‐
176       ate both “[a]” and “[b]” before invoking the expr command.
177
178   MATH FUNCTIONS
179       When the expression parser encounters a mathematical function  such  as │
180       sin($x),  it replaces it with a call to an ordinary Tcl function in the │
181       tcl::mathfunc namespace.  The processing of an expression such as:      │
182              expr {sin($x+$y)}                                                
183       is the same in every way as the processing of:                          │
184              expr {[tcl::mathfunc::sin [expr {$x+$y}]]}                       
185       which in turn is the same as the processing of:                         │
186              tcl::mathfunc::sin [expr {$x+$y}]                                
187
188       The executor will search for tcl::mathfunc::sin using the  usual  rules │
189       for  resolving  functions in namespaces. Either ::tcl::mathfunc::sin or │
190       [namespace current]::tcl::mathfunc::sin will satisfy the  request,  and │
191       others may as well (depending on the current namespace path setting).   │
192
193       See  the mathfunc(n) manual page for the math functions that are avail‐ │
194       able by default.
195
196   TYPES, OVERFLOW, AND PRECISION
197       All internal computations involving integers are done  calling  on  the │
198       LibTomMath  multiple  precision integer library as required so that all │
199       integer calculations are performed exactly.  Note that in Tcl  releases │
200       prior  to  8.5,  integer  calculations were performed with one of the C │
201       types long int or Tcl_WideInt, causing  implicit  range  truncation  in │
202       those  calculations  where  values overflowed the range of those types. │
203       Any code that relied on these implicit truncations will need to explic‐ │
204       itly  add  int()  or wide() function calls to expressions at the points │
205       where such truncation is required to take place.
206
207       All internal computations involving floating-point are done with the  C
208       type  double.   When  converting  a  string to floating-point, exponent
209       overflow is detected and results in the double value of Inf or -Inf  as
210       appropriate.  Floating-point overflow and underflow are detected to the
211       degree supported by the hardware, which is generally pretty reliable.
212
213       Conversion among internal representations for integer,  floating-point,
214       and  string  operands  is done automatically as needed.  For arithmetic
215       computations, integers are used until  some  floating-point  number  is
216       introduced, after which floating-point is used.  For example,
217              expr {5 / 4}
218       returns 1, while
219              expr {5 / 4.0}
220              expr {5 / ( [string length "abcd"] + 0.0 )}
221       both return 1.25.  Floating-point values are always returned with a “.
222       or an “e” so that they will not look like integer values.  For example,
223              expr {20.0/5.0}
224       returns 4.0, not 4.
225
226   STRING OPERATIONS
227       String values may be used as  operands  of  the  comparison  operators,
228       although the expression evaluator tries to do comparisons as integer or
229       floating-point when it can, except in the case of the eq and ne  opera‐
230       tors.  If one of the operands of a comparison is a string and the other
231       has a numeric value, a canonical string representation of  the  numeric
232       operand value is generated to compare with the string operand.  Canoni‐
233       cal string representation for integer values is a decimal  string  for‐
234       mat.  Canonical string representation for floating-point values is that
235       produced by the %g format specifier of Tcl's format command.  For exam‐
236       ple, the commands
237              expr {"0x03" > "2"}
238              expr {"0y" < "0x12"}
239       both  return 1.  The first comparison is done using integer comparison,
240       and the second is done using string comparison after the second operand
241       is converted to the string 18.  Because of Tcl's tendency to treat val‐
242       ues as numbers whenever possible, it is not generally a  good  idea  to
243       use  operators  like  == when you really want string comparison and the
244       values of the operands could be arbitrary;  it is better in these cases
245       to use the eq or ne operators, or the string command instead.
246

PERFORMANCE CONSIDERATIONS

248       Enclose expressions in braces for the best speed and the smallest stor‐
249       age requirements.  This allows the Tcl bytecode  compiler  to  generate
250       the best code.
251
252       As  mentioned above, expressions are substituted twice: once by the Tcl
253       parser and once by the expr command.  For example, the commands
254              set a 3
255              set b {$a + 2}
256              expr $b*4
257       return 11, not a multiple of 4.  This is because the  Tcl  parser  will
258       first  substitute $a + 2 for the variable b, then the expr command will
259       evaluate the expression $a + 2*4.
260
261       Most expressions do  not  require  a  second  round  of  substitutions.
262       Either  they are enclosed in braces or, if not, their variable and com‐
263       mand substitutions yield numbers or  strings  that  do  not  themselves
264       require  substitutions.   However,  because  a few unbraced expressions
265       need two rounds of substitutions, the bytecode compiler must emit addi‐
266       tional  instructions to handle this situation.  The most expensive code
267       is required for unbraced expressions  that  contain  command  substitu‐
268       tions.   These  expressions  must be implemented by generating new code
269       each time the expression is executed.  When the expression is  unbraced │
270       to allow the substitution of a function or operator, consider using the │
271       commands documented  in  the  mathfunc(n)  or  mathop(n)  manual  pages │
272       directly instead.
273

EXAMPLES

275       Define  a  procedure  that computes an “interesting” mathematical func‐
276       tion:
277              proc tcl::mathfunc::calc {x y} {
278                  expr { ($x**2 - $y**2) / exp($x**2 + $y**2) }
279              }
280
281       Convert polar coordinates into cartesian coordinates:
282              # convert from ($radius,$angle)
283              set x [expr { $radius * cos($angle) }]
284              set y [expr { $radius * sin($angle) }]
285
286       Convert cartesian coordinates into polar coordinates:
287              # convert from ($x,$y)
288              set radius [expr { hypot($y, $x) }]
289              set angle  [expr { atan2($y, $x) }]
290
291       Print a message describing the relationship of  two  string  values  to
292       each other:
293              puts "a and b are [expr {$a eq $b ? {equal} : {different}}]"
294
295       Set  a  variable  to whether an environment variable is both defined at
296       all and also set to a true boolean value:
297              set isTrue [expr {
298                  [info exists ::env(SOME_ENV_VAR)] &&
299                  [string is true -strict $::env(SOME_ENV_VAR)]
300              }]
301
302       Generate a random integer in the range 0..99 inclusive:
303              set randNum [expr { int(100 * rand()) }]
304

SEE ALSO

306       array(n), for(n), if(n), mathfunc(n), mathop(n), namespace(n), proc(n),
307       string(n), Tcl(n), while(n)
308

KEYWORDS

310       arithmetic, boolean, compare, expression, fuzzy comparison
311
313       Copyright (c) 1993 The Regents of the University of California.
314       Copyright (c) 1994-2000 Sun Microsystems Incorporated.
315       Copyright (c) 2005 by Kevin B. Kenny <kennykb@acm.org>. All rights reserved.
316
317
318
319Tcl                                   8.5                              expr(n)
Impressum