There may be any number of variable substitutions in a single word. Variable substitution is not performed on words enclosed in braces.
Note that variables may contain character sequences other than those listed above, but in that case other mechanisms must be used to access them (e.g., via the set command's single-argument form).
Backslash substitution is not performed on words enclosed in braces, except for backslash-newline as described above.
Substitutions take place from left to right, and each substitution is evaluated completely before attempting to evaluate the next. Thus, a sequence like
set y [set x 0][incr x][incr x]
will always set the variable y to the value, 012.
For the most part, Tcl strings can be thought of as strings of characters instead of sequences of code points and following common usage, command descriptions refer to them as such. However, the distinction is to be noted as some characters may have multiple representations as Unicode code point sequences and in operations like comparisons, Tcl compares individual code points and not individual abstract characters.
While all values are strings, individual commands may treat or expect their arguments to be representations of data of a particular type. For example, the incr command expects its operands to be integers.
The most important consequence of the EIAS principle is that all commands must treat arguments that have a particular string representation exactly the same irrespective of how that value was produced. Thus the incr command must treat 100 produced by appending 0 to 10 exactly the same as 100 produced by multiplying 10 by itself.
Note this EIAS principle is only true at a conceptual level and for reasons of efficiency the implementation may choose different internal representations for a value depending on its usage. For example, arithmetic operations on integers may internally store the value as a native machine word. Similarly, a binary string is a sequence of Unicode code points in the range U+0000 to U+00FF and may be stored as an array of bytes. In all cases this internal representation is irrelevant at the Tcl language level but exposed in the Tcl C API.
expr 8.2 + 6
evaluates to 14.2. Expressions differ from C expressions in the way that operands are specified. Expressions also support non-numeric operands, string comparisons, and some additional operators not found in C.
When the result of expression is an integer, it is in decimal form, and when the result is a floating-point number, it is in the form produced by the %g format specifier of format.
At any point in the expression except within double quotes or braces, # is the beginning of a comment, which lasts to the end of the line or the end of the expression, whichever comes first.
Each operand has one of the following forms:
A floating-point number may be take any of several common decimal formats, and may use the decimal point ., e or E for scientific notation, and the sign characters + and -. The following are all valid floating-point numbers: 2.1, 3., 6e4, 7.91e+16. The strings Inf and NaN, in any combination of case, are also recognized as floating point values. An operand that doesn't have a numeric interpretation must be quoted with either braces or with double quotes.
Digits in any numeric value may be separated with one or more underscore characters, "_". A separator may only appear between digits, not appear at the start of a numeric value, between the leading 0 and radix specifier, or at the end of a numeric value. Here are some examples:
expr 100_000_000 100000000 expr 0xffff_ffff 4294967295 format 0x%x 0b1111_1110_1101_1011 0xfedb expr 3_141_592_653_589e-1_2 3.141592653589
An argument of a function, or an element of a list, may be prefixed by {*}, as in the argument expansion rule for Tcl: its value is taken as a list, and each element of that list becomes a separate argument of the function, or a separate element of the list. For instance, if the value of L is 3 1 2, max({*}$L, 0) is max(3, 1, 2, 0) and (0, {*}$L) is 0 3 1 2. {*} is recognized only when it is immediately followed by the start of an operand (a number, a variable, a bracket, a brace, a quote, a name or an open parenthesis); elsewhere, as in {*} eq "*", it is a braced string. It is an error to use {*} anywhere but before an argument of a function or an element of a list.
Because expr parses and performs substitutions on values that have already been parsed and substituted by Tcl, it is usually best to enclose expressions in braces to avoid the first round of substitutions by Tcl.
Below are some examples of simple expressions where the value of a is 3 and the value of b is 6. The command on the left side of each line produces the value on the right side.
expr {3.1 + $a} 6.1
expr {2 + "$a.$b"} 5.6
expr {4*[llength {6 2}]} 8
expr {{word one} < "word $a"} 0
Unless otherwise specified, operators accept non-numeric operands. The value of a boolean operation is 1 if true, 0 otherwise. See also string is boolean. The valid operators, most of which are also available as commands in the ::tcl::mathop namespace (see mathop(n)), are listed below, grouped in decreasing order of precedence:
When applied to integers, division and remainder can be considered to partition the number line into a sequence of adjacent non-overlapping pieces, where each piece is the size of the divisor; the quotient identifies which piece the dividend lies within, and the remainder identifies where within that piece the dividend lies. A consequence of this is that the result of “-57 / 10” is always -6, and the result of “-57 % 10” is always 3.
The exponentiation operator promotes types in the same way that the multiply and divide operators do, and the result is is the same as the result of pow. Exponentiation and assignment group right-to-left within a precedence level. Other binary operators group left-to-right. For example, the value of
expr {4*2 < 7}
is 0, while the value of
expr {2**3**2}
is 512.
As in C, &&, ||, and ?: feature “lazy evaluation”, which means that operands are not evaluated if they are not needed to determine the outcome. For example, in
expr {$v?[a]:[b]}
only one of [a] or [b] is evaluated, depending on the value of $v. This is not true of the normal Tcl parser, so it is normally recommended to enclose the arguments to expr in braces. Without braces, as in expr $v ? [a] : [b] both [a] and [b] are evaluated before expr is even called.
For more details on the results produced by each operator, see the documentation for C.
expr {sin($x+$y)}
is the same in every way as the evaluation of
expr {[::tcl::mathfunc::sin [expr {$x+$y}]]}
which in turn is the same as the evaluation of
::tcl::mathfunc::sin [expr {$x+$y}]
::tcl::mathfunc::sin is resolved as described in NAMESPACE RESOLUTION in the namespace(n) documentation. Given the default value of namespace path, [namespace current]::tcl::mathfunc::sin or ::tcl::mathfunc::sin are the typical resolutions.
As in C, a mathematical function may accept multiple arguments separated by commas. Thus,
expr {hypot($x,$y)}
becomes
::tcl::mathfunc::hypot $x $y
See the mathfunc(n) documentation for the math functions that are available by default.
Conversion among internal representations for integer, floating-point, and string operands is done automatically as needed. For arithmetic computations, integers are used until some floating-point number is introduced, after which floating-point values are used. For example,
expr {5 / 4}
returns 1, while
expr {5 / 4.0}
expr {5 / ( [string length "abcd"] + 0.0 )}
both return 1.25. A floating-point result can be distinguished from an integer result by the presence of either “.” or “e”.
For example,
expr {20.0/5.0}
returns 4.0, not 4.
In the following example, the value of the expression is 11 because the Tcl parser first substitutes $b and expr then substitutes $a as part of evaluating the expression “$a + 2*4”. Enclosing the expression in braces would result in a syntax error as $b does not evaluate to a numeric value.
set a 3
set b {$a + 2}
expr $b*4
When an expression is generated at runtime, like the one above is, the bytecode compiler must ensure that new code is generated each time the expression is evaluated. This is the most costly kind of expression from a performance perspective. In such cases, consider directly using the commands described in the mathfunc(n) or mathop(n) documentation instead of expr.
Most expressions are not formed at runtime, but are literal strings or contain substitutions that don't introduce other substitutions. To allow the bytecode compiler to work with an expression as a string literal at compilation time, ensure that it contains no substitutions or that it is enclosed in braces or otherwise quoted to prevent Tcl from performing substitutions, allowing expr to perform them instead.
If it is necessary to include a non-constant expression string within the wider context of an otherwise-constant expression, the most efficient technique is to put the varying part inside a recursive expr, as this at least allows for the compilation of the outer part, though it does mean that the varying part must itself be evaluated as a separate expression. Thus, in this example the result is 20 and the outer expression benefits from fully cached bytecode compilation.
set a 3
set b {$a + 2}
expr {[expr $b] * 4}
In general, you should enclose your expression in braces wherever possible, and where not possible, the argument to expr should be an expression defined elsewhere as simply as possible. It is usually more efficient and safer to use other techniques (e.g., the commands in the ::tcl::mathop namespace) than it is to do complex expression generation.
expr {"0x03" > "2"}
A string comparison whose result is 1:
expr {"0y" > "0x12"}
A forced string comparison whose result is 0:
expr {"0x03" gt "2"}
A procedure whose body is an expression script (see rule [1] of the Tcl manual page): the body is one expression.
proc hypot {a b} {( sqrt($a**2 + $b**2) )}
lmap x {1 2 3} {( $x * $x )}
Build lists of computed values, for instance coordinates for a canvas:
set pairs [lmap a $xs b $ys {( $a, $b )}]
set coords [lmap x $xs {( $x, sin($x) )}]
Compute a value with an expression substitution, the short form of [expr {...}] in a word:
set area [( $width * $height )]
puts "half: [( $area / 2.0 )]"
A procedure whose body is an expression script with raw commands:
proc dot {u v} {(
s = 0;
foreach a $u b $v {( s = $s + $a*$b )};
$s
)}
A sequence of computations, each result stored in a variable:
expr { x = 5*$y + 6*$z; w = $x**2 + $y**2; v = $w**2 + $y**2 }
The distance between two points, given as lists {x y}, with a tuple assignment in an expression script:
proc distance {p q} {(
((x0, y0), (x1, y1)) = ($p, $q);
hypot($x1 - $x0, $y1 - $y0)
)}
Define a procedure that computes an “interesting” mathematical function:
proc ::tcl::mathfunc::calc {x y} {
expr { ($x**2 - $y**2) / exp($x**2 + $y**2) }
}
Convert polar coordinates into cartesian coordinates:
# convert from ($radius,$angle)
set x [expr { $radius * cos($angle) }]
set y [expr { $radius * sin($angle) }]
Convert cartesian coordinates into polar coordinates:
# convert from ($x,$y)
set radius [expr { hypot($y, $x) }]
set angle [expr { atan2($y, $x) }]
Print a message describing the relationship of two string values to each other:
puts "a and b are [expr {$a eq $b ? {equal} : {different}}]"
Set a variable indicating whether an environment variable is defined and has value of true:
set isTrue [expr {
# Does the environment variable exist, and...
[info exists ::env(SOME_ENV_VAR)] &&
# ...does it contain a proper true value?
[string is true -strict $::env(SOME_ENV_VAR)]
}]
Generate a random integer in the range 0..99 inclusive:
set randNum [expr { int(100 * rand()) }]
If any of the -nobackslashes, -nocommands, -noexpr, or -novariables are specified, then the corresponding substitutions are not performed. For example, if -nocommands is specified, command substitution is not performed: open and close brackets are treated as ordinary characters with no special interpretation. Expression substitution “[(”... (see rule [7] of the Tcl manual page) is controlled by -noexpr, not by -nocommands: with -noexpr, an open bracket followed by an open parenthesis is an ordinary character.
If any of the -backslashes, -commands, -expr, or -variables are specified, then only the corresponding substitutions are performed. This means that the following lines are equivalent:
subst -nobackslashes -nocommands $string subst -variables $string
It is not allowed to combine positive and negated options.
Note that the substitution of one kind can include substitution of other kinds. For example, even when the -novariables option is specified, command substitution is performed without restriction. This means that any variable substitution necessary to complete the command substitution will still take place. Likewise, any command substitution necessary to complete a variable substitution will take place, even when -nocommands is specified. See the EXAMPLES below.
If an error occurs during substitution, then subst will return that error. If a break exception occurs during command or variable substitution, the result of the whole substitution will be the string (as substituted) up to the start of the substitution that raised the exception. If a continue exception occurs during the evaluation of a command or variable substitution, an empty string will be substituted for that entire command or variable substitution (as long as it is well-formed Tcl.) If a return exception occurs, or any other return code is returned during command or variable substitution, then the returned value is substituted for that substitution. See the EXAMPLES below. In this way, all exceptional return codes are “caught” by subst. The subst command itself will either return an error, or will complete successfully.
set a 44
subst {xyz {$a}}
returns “xyz {44}”, not “xyz {$a}” and the script
set a "p\} q \{r"
subst {xyz {$a}}
returns “xyz {p} q {r}”, not “xyz {p\} q \{r}”.
When command substitution is performed, it includes any variable substitution necessary to evaluate the script.
set a 44
subst -novariables {$a [format $a]}
returns “$a 44”, not “$a $a”. Similarly, when variable substitution is performed, it includes any command substitution necessary to retrieve the value of the variable.
proc b {} {return c}
array set a {c c [b] tricky}
subst -nocommands {[b] $a([b])}
returns “[b] c”, not “[b] tricky”.
The continue and break exceptions allow command substitutions to prevent substitution of the rest of the command substitution and the rest of string respectively, giving script authors more options when processing text using subst. For example, the script
subst {abc,[break],def}
returns “abc,”, not “abc,,def” and the script
subst {abc,[continue;expr {1+2}],def}
returns “abc,,def”, not “abc,3,def”.
Other exceptional return codes substitute the returned value
subst {abc,[return foo;expr {1+2}],def}
returns “abc,foo,def”, not “abc,3,def” and
subst {abc,[return -code 10 foo;expr {1+2}],def}
also returns “abc,foo,def”, not “abc,3,def”.