TIP 759 series: changes to Tcl(n), expr(n), subst(n)

Green text: added. Underlined in green: modified terms. Removed text is not shown. Compared with the 9.1 trunk.
NAME
Tcl — Tool Command Language
SYNOPSIS
DESCRIPTION
SYNTAX
    [1] Scripts.
    Command scripts.
    Expression scripts.
    [2] Evaluation.
    Evaluation of a command.
    Evaluation of an expression.
    [3] Words.
    Words of a command.
    Operands of an expression.
    [4] Double quotes.
    [5] Argument expansion.
    Argument expansion in a command.
    Argument expansion in an expression.
    [6] Braces.
    [7] Script substitution.
    Command substitution.
    Expression substitution.
    [8] Variable substitution.
    $name
    $name(index)
    ${name}
    [9] Backslash substitution.
    Backslash substitution in a command.
    \a
    \b
    \f
    \n
    \r
    \t
    \v
    \<newline>whiteSpace
    \\
    \ooo
    \xhh
    \uhhhh
    \Uhhhhhhhh
    Backslash substitution in an expression.
    [10] Comments.
    Comments in a command script.
    Comments in an expression.
    [11] Order of substitution.
    Order of substitution in a command.
    Order of substitution in an expression.
    [12] Substitution and word boundaries.
TCL VALUES
KEYWORDS

NAME

Tcl — Tool Command Language

SYNOPSIS

Summary of Tcl language syntax.

DESCRIPTION

SYNTAX

The following rules define the syntax and semantics of the Tcl language:

    [1] Scripts.
    A Tcl script is a string of one of two kinds: a command script, made of one or more commands, or an expression script, made of one expression. Commands that take a script as an argument, such as the body of proc or foreach, accept both kinds.

    Command scripts.
    A command script contains one or more commands. Semi-colons and newlines are command separators unless quoted as described below. Close brackets are command terminators during command substitution (see below) unless quoted.

    Expression scripts.
    A script that begins with an open parenthesis (“(”) and ends with a close parenthesis (“)”) (a newline may follow it) is an expression script: the whole script, parentheses included, is one expression, as described in the expr manual page. Semi-colons and newlines inside it are not command separators. For instance, the body of “proc hypot {a b} {( sqrt($a**2 + $b**2) )}” is an expression script, and so is “("Hi there")”, whose result is the string Hi there. Only a whole script is tested: in a script of several commands, a command that begins with an open parenthesis is an ordinary command. Conversely, a script such as “(cmd) (x)” is an expression script, and an error. During expression substitution (see below), the expression ends at the first close parenthesis that is immediately followed by a close bracket and leaves the parentheses of the expression balanced: “)]” is one symbol.

    [2] Evaluation.
    How a script is evaluated depends on its kind.

    Evaluation of a command.
    A command is evaluated in two steps. First, the Tcl interpreter breaks the command into words and performs substitutions as described below. These substitutions are performed in the same way for all commands. Secondly, the first word is used to locate a routine to carry out the command, and the remaining words of the command are passed to that routine. The routine is free to interpret each of its words in any way it likes, such as an integer, variable name, list, or Tcl script. Different commands interpret their words differently. There is one exception: a command made of a single word that is a single expression substitution, such as “[( $x * 3 )]” alone on a line, is evaluated as the expression; its value is the result of the command and is not used as a command name.

    Evaluation of an expression.
    An expression is evaluated as by the expr command, in two steps. First, it is broken into operands and operators (see rule [3]); the precedence of the operators, given in the expr manual page, and parentheses determine the order in which the operators apply. Secondly, each operator is applied to the values of its operands. Substitutions in an operand are performed when that operand is evaluated, not before (see rule [11]). No routine is located: the value of the expression is the result.

    [3] Words.
    How a script is divided into words depends on its kind (rule [1]).

    Words of a command.
    Words of a command are separated by white space (except for newlines, which are command separators).

    Operands of an expression.
    An expression is a sequence of operands and operators, as described in the expr manual page; its operands play the role of words. Unlike in a command, white space, including newlines, does not separate operands: it is ignored, except that it ends a number or a name. An operand ends at the first character that cannot continue it, such as white space, an operator, a comma or a parenthesis. Two operands must be separated by an operator, or by a comma between the arguments of a function or the elements of a list; otherwise the expression is an error, as in 1 2 or "a""b", whereas "a"eq"a" is valid. An operand is a number, a boolean value, a quoted word (rule [4]), a braced word (rule [6]), a substitution (rules [7] to [9]), a function call or a list. The value of a substituted operand is always a single operand: it is never parsed again as an expression.

    [4] Double quotes.
    If the first character of a word, or of an operand of an expression, is double-quote (“"”) then the word is terminated by the next double-quote character. If semi-colons, close brackets, or white space characters (including newlines) appear between the quotes then they are treated as ordinary characters and included in the word. Command substitution, expression substitution, variable substitution, and backslash substitution are performed on the characters between the quotes as described below. The double-quotes are not retained as part of the word.

    [5] Argument expansion.
    A word of a command, or an operand of an expression, may be expanded into several.

    Argument expansion in a command.
    If a word starts with the string “{*}” followed by a non-whitespace character, then the leading “{*}” is removed and the rest of the word is parsed and substituted as any other word. After substitution, the word is parsed as a list (without command or variable substitutions; backslash substitutions are performed as is normal for a list and individual internal words may be surrounded by either braces or double-quote characters), and its words are added to the command being substituted. For instance, “cmd a {*}{b [c]} d {*}{$e f {g h}}” is equivalent to “cmd a b {[c]} d {$e} f {g h}”.

    Argument expansion in an expression.
    If an argument of a function, or an element of a list, starts with the string “{*}” immediately followed by the start of an operand, then the leading “{*}” is removed and the rest of the operand is evaluated as any other operand. Its value is then parsed as a list, as in a command, and each of its elements 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, then “max({*}$L, 0)” is equivalent to “max(3, 1, 2, 0)”. Anywhere else in an expression, this prefix is an error; but “{*}” followed by white space or by an operator, as in “{*} eq "*"”, is the braced string * (rule [6]).

    [6] Braces.
    If the first character of a word, or of an operand of an expression, is an open brace (“{”) and rule [5] does not apply, then the word is terminated by the matching close brace (“}”). Braces nest within the word: for each additional open brace there must be an additional close brace (however, if an open brace or close brace within the word is quoted with a backslash then it is not counted in locating the matching close brace). No substitutions are performed on the characters between the braces except for backslash-newline substitutions described below, nor do semi-colons, newlines, close brackets, or white space receive any special interpretation. The word will consist of exactly the characters between the outer braces, not including the braces themselves.

    [7] Script substitution.
    If a word contains an open bracket (“[”) then Tcl performs script substitution: the characters following the open bracket form a script (rule [1]), which is evaluated; its result is substituted into the word in place of the brackets and all of the characters between them. The kind of the script decides where it ends and how it is evaluated. There may be any number of script substitutions in a single word. Script substitution is not performed on words enclosed in braces.

    Command substitution.
    If the open bracket is not immediately followed by an open parenthesis, the script is a command script, and Tcl performs command substitution. To do this it invokes the Tcl interpreter recursively to process the characters following the open bracket as a Tcl script. The script may contain any number of commands and must be terminated by a close bracket (“]”). The result of the script (i.e. the result of its last command) is the result of the substitution. To substitute the result of a command whose name begins with an open parenthesis, put a space after the open bracket.

    Expression substitution.
    If the open bracket is immediately followed by an open parenthesis (“[(”) the script is an expression script, and Tcl performs expression substitution. The script extends from that open parenthesis to the first close parenthesis that is immediately followed by a close bracket (“)]”) and leaves the parentheses balanced; parentheses inside braces, quotes and nested substitutions are not counted. It is evaluated as an expression, as by the expr command, and the value of the expression is the result of the substitution. For instance, “set area [( $w * $h )]” is equivalent to “set area [expr {$w * $h}]”. A command made of a single expression substitution is described in rule [2].

    [8] Variable substitution.
    If a word contains a dollar-sign (“$”) followed by one of the forms described below, then Tcl performs variable substitution: the dollar-sign and the following characters are replaced in the word by the value of a variable. Variable substitution may take any of the following forms:

    $name
    Name is the name of a scalar variable; the name is a sequence of one or more characters that are a letter, digit, underscore, or namespace separators (two or more colons). Letters and digits are only the standard ASCII ones (0–9, A–Z and a–z).

    $name(index)
    Name gives the name of an array variable and index gives the name of an element within that array. Name must contain only letters, digits, underscores, and namespace separators, and may be an empty string. Letters and digits are only the standard ASCII ones (0–9, A–Z and a–z). Command substitutions, variable substitutions, and backslash substitutions are performed on the characters of index.

    ${name}
    Name is the name of a scalar variable or array element. It may contain any characters whatsoever except for close braces. It indicates an array element if name is in the form “arrayName(index)” where arrayName does not contain any open parenthesis characters, “(”, or close brace characters, “}”, and index can be any sequence of characters except for close brace characters. No further substitutions are performed during the parsing of name.

    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).

    [9] Backslash substitution.
    Backslash substitution is performed differently in a command and in an expression.

    Backslash substitution in a command.
    If a backslash (“\”) appears within a word then backslash substitution occurs. In all cases but those described below the backslash is dropped and the following character is treated as an ordinary character and included in the word. This allows characters such as double quotes, close brackets, and dollar signs to be included in words without triggering special processing. The following table lists the backslash sequences that are handled specially, along with the value that replaces each sequence.

    \a
    Audible alert (bell) (Unicode U+000007).

    \b
    Backspace (Unicode U+000008).

    \f
    Form feed (Unicode U+00000C).

    \n
    Newline (Unicode U+00000A).

    \r
    Carriage-return (Unicode U+00000D).

    \t
    Tab (Unicode U+000009).

    \v
    Vertical tab (Unicode U+00000B).

    \<newline>whiteSpace
    A single space character replaces the backslash, newline, and all spaces and tabs after the newline. This backslash sequence is unique in that it is replaced in a separate pre-pass before the command is actually parsed. This means that it will be replaced even when it occurs between braces, and the resulting space will be treated as a word separator if it is not in braces or quotes.

    \\
    Backslash (“\”).

    \ooo
    The digits ooo (one, two, or three of them) give a eight-bit octal value for the Unicode character that will be inserted, in the range 000–377 (i.e., the range U+000000–U+0000FF). The parser will stop just before this range overflows, or when the maximum of three digits is reached. The upper bits of the Unicode character will be 0.

    \xhh
    The hexadecimal digits hh (one or two of them) give an eight-bit hexadecimal value for the Unicode character that will be inserted. The upper bits of the Unicode character will be 0 (i.e., the character will be in the range U+000000–U+0000FF).

    \uhhhh
    The hexadecimal digits hhhh (one, two, three, or four of them) give a sixteen-bit hexadecimal value for the Unicode character that will be inserted. The upper bits of the Unicode character will be 0 (i.e., the character will be in the range U+000000–U+00FFFF).

    \Uhhhhhhhh
    The hexadecimal digits hhhhhhhh (one up to eight of them) give a twenty-one-bit hexadecimal value for the Unicode character that will be inserted, in the range U+000000–U+10FFFF. The parser will stop just before this range overflows, or when the maximum of eight digits is reached. The upper bits of the Unicode character will be 0.

    Backslash substitution is not performed on words enclosed in braces, except for backslash-newline as described above.

    Backslash substitution in an expression.
    In an expression, backslash substitution is performed only where it is performed in a word: between the double quotes of a quoted operand (rule [4]), in the index of an array variable, and in a command substitution. Elsewhere, a backslash is an error, except a backslash-newline, which is white space, and a backslash directly followed by a letter, which begins a user-defined operator, as $U \dot $V (see expr). Some operator names look like backslash sequences, such as \times or \neg: in a braced expression they are operators, but in an expression written between double quotes, as in expr "$a \times $b", the Tcl parser first replaces \t or \n (rule [4]). Thus “"\x31" + 1” is 2, but “\x31 + 1” calls a user-defined operator \x31 (an error unless the command tcl::mathop::x31 exists), and “1 + \ 2” is an error.

    [10] Comments.
    Comments are recognized differently in a command script and in an expression.

    Comments in a command script.
    If a hash character (“#”) appears at a point where Tcl is expecting the first character of the first word of a command, then the hash character and the characters that follow it, up through the next newline, are treated as a comment and ignored. The comment character only has significance when it appears at the beginning of a command.

    Comments in an expression.
    If a hash character (“#”) appears at a point where an operand is expected, then the hash character and the characters that follow it, up through the next newline, are treated as a comment and ignored, as described in the expr manual page.

    [11] Order of substitution.
    The order of substitutions depends on the kind of script.

    Order of substitution in a command.
    Each character is processed exactly once by the Tcl interpreter as part of creating the words of a command. For example, if variable substitution occurs then no further substitutions are performed on the value of the variable; the value is inserted into the word verbatim. If command substitution occurs then the nested command is processed entirely by the recursive call to the Tcl interpreter; no substitutions are performed before making the recursive call and no additional substitutions are performed on the result of the nested script.

    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.

    Order of substitution in an expression.
    Substitutions in an expression are performed when the operand that contains them is evaluated, not before the expression is evaluated. Operands are evaluated from left to right, except that the operators &&, || and ?: evaluate only the operands they need. Thus “expr {$n != 0 && [check $n]}” does not invoke check when n is 0. As in a command, the value of a substitution is not substituted again.

    [12] Substitution and word boundaries.
    Substitutions do not affect the word boundaries of a command, except for argument expansion as specified in rule [5]. For example, during variable substitution the entire value of the variable becomes part of a single word, even if the variable's value contains spaces. Likewise, in an expression, a substitution always gives a single operand, except for argument expansion: if the value of x is 1 + 1, then “$x * 2” multiplies the string 1 + 1 by 2, which is an error, and does not compute 4.

TCL VALUES

Conceptually, all values in Tcl are strings, or to be precise, sequences of Unicode code points. This characteristic of all values being strings is commonly referred to as the Everything Is A String (EIAS) principle.

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.

KEYWORDS

backslash, command, comment, expression, script, substitution, variable
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
NAME
expr — Evaluate an expression
SYNOPSIS
DESCRIPTION
OPERANDS
A numeric value
A boolean value
A variable
A string enclosed in double-quotes
A string enclosed in braces.
A Tcl command enclosed in brackets
A raw command
An expression enclosed in [( and )]
A function call.
A list.
OPERATORS
- + ~ !
\name
**
* / %
x \name y
+ -
<< >>
< > <= >=
lt gt le ge
== !=
eq ne
in ni
&
^
|
&&
||
x ? y : z
name = x
(name, name, ...) = x
x ; y
MATH FUNCTIONS
TYPES, OVERFLOW, AND PRECISION
PERFORMANCE CONSIDERATIONS
EXAMPLES
SEE ALSO
KEYWORDS

NAME

expr — Evaluate an expression

SYNOPSIS

expr arg ?arg arg ...?

DESCRIPTION

Concatenates args, separated by a space, into an expression, and evaluates that expression, returning its value. The operators permitted in an expression include a subset of the operators permitted in C expressions. For those operators common to both Tcl and C, Tcl applies the same meaning and precedence as the corresponding C operators. The value of an expression is often a numeric result, either an integer or a floating-point value, but may also be a non-numeric value. For example, the expression

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.

OPERANDS

An expression consists of a combination of operands, operators, parentheses and commas, possibly with whitespace between any of these elements, which is ignored. Each operand is interpreted as a numeric value if at all possible.

Each operand has one of the following forms:

A numeric value

Either integer or floating-point. The first two characters of an integer may also be 0d for decimal, 0b for binary, 0o for octal or 0x for hexadecimal.

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

A boolean value
Using any form understood by string is boolean.

A variable
Using standard $ notation. The value of the variable is the value of the operand.

A string enclosed in double-quotes
Backslash, variable, and command substitution are performed according to the rules for Tcl.

A string enclosed in braces.
The operand is treated as a braced value according to the rule for braces in Tcl.

A Tcl command enclosed in brackets
Command substitution is performed as according to the command substitution rule for Tcl.

A raw command
A command without brackets, when its name is one of concat, dict, for, foreach, global, if, incr, lappend, lassign, lindex, llength, lmap, lrange, lset, namespace, return, string, switch, upvar, variable or while, followed by a space. The command ends at a semicolon, or at an operator or a close parenthesis that begins a word, or at the end of the expression; its result is the value of the operand. For instance llength $list + 1 is [llength $list] + 1. This form is provisional.

An expression enclosed in [( and )]
Expression substitution, as described in the script substitution rule ([7]) for Tcl: the value of the expression between the brackets is the value of the operand.

A function call.
This is mathematical function such as sin($x), whose arguments have any of the above forms for operands. See MATH FUNCTIONS below for a discussion of how mathematical functions are handled.

A list.
Two or more expressions separated by commas, in parentheses that do not follow a function name: (a, b, ...). The value is the list of the values of the expressions, as built by the list command; it is not converted to a number. Lists may be nested: the value of ((1, 2), 3) is {1 2} 3. A parenthesized expression without a comma is not a list. A comma outside of any parentheses makes the whole expression a list, as if it were enclosed in parentheses: 1, 2 is 1 2, and the parentheses of an expression substitution may close early, as in [(1, 2), (3, 4)], which is {1 2} {3 4}.

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

OPERATORS

For operators having both a numeric mode and a string mode, the numeric mode is chosen when all operands have a numeric interpretation. The integer interpretation of an operand is preferred over the floating-point interpretation. To ensure string operations on arbitrary values it is generally a good idea to use eq, ne, or the string command instead of more versatile operators such as ==.

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:

- + ~ !
Unary minus, unary plus, bit-wise NOT, logical NOT. These operators may only be applied to numeric operands, and bit-wise NOT may only be applied to integers.

\name
User-defined unary operator: \name x is the result of the command tcl::mathop::name x. name begins with a letter, followed by letters, digits and underscores. The command is resolved as the functions of tcl::mathfunc (see MATH FUNCTIONS): relative to the current namespace, then in the global namespace.

**
Exponentiation. Valid for numeric operands. The maximum exponent value that Tcl can handle if the first number is an integer > 1 is 268435455.

* / %
Multiply and divide, which are valid for numeric operands, and remainder, which is valid for integers. The remainder, an absolute value smaller than the absolute value of the divisor, has the same sign as the divisor.

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.

x \name y
User-defined binary operator, with the precedence of * and grouping left-to-right: x \name y is the result of the command tcl::mathop::name x y, resolved as for the unary form. For instance, with “proc tcl::mathop::dot {u v} {...}” returning the dot product of two vectors, “$U \dot $V” is the dot product of U and V, and “$a + $U \dot $V * 2” is “$a + (($U \dot $V) * 2)”. A user-defined operator is recognized only in an expression read by the expression parser: in braces, or in an expression substitution or an expression script. Between double quotes, the Tcl parser performs backslash substitution first (see Tcl, rule [4]).

+ -
Add and subtract. Valid for numeric operands.

<< >>
Left and right shift. Valid for integers. A right shift always propagates the sign bit.

< > <= >=
Boolean numeric-preferring comparisons: less than, greater than, less than or equal, and greater than or equal. If either argument is not numeric, the comparison is done using UNICODE string comparison, as with the string comparison operators below, which have the same precedence.

lt gt le ge
Boolean string comparisons: less than, greater than, less than or equal, and greater than or equal. These always compare values using their UNICODE strings (also see string compare), unlike with the numeric-preferring comparisons above, which have the same precedence.

== !=
Boolean equal and not equal.

eq ne
Boolean string equal and string not equal.

in ni
List containment and negated list containment. The first argument is interpreted as a string, the second as a list. in tests for membership in the list, and ni is the inverse.

&
Bit-wise AND. Valid for integer operands.

^
Bit-wise exclusive OR. Valid for integer operands.

|
Bit-wise OR. Valid for integer operands.

&&
Logical AND. If both operands are true, the result is 1, or 0 otherwise. This operator evaluates lazily; it only evaluates its second operand if it must in order to determine its result. This operator evaluates lazily; it only evaluates its second operand if it must in order to determine its result.

||
Logical OR. If both operands are false, the result is 0, or 1 otherwise. This operator evaluates lazily; it only evaluates its second operand if it must in order to determine its result.

x ? y : z
If-then-else, as in C. If x is true , the result is the value of y. Otherwise the result is the value of z. This operator evaluates lazily; it evaluates only one of y or z.

name = x
Assignment, as in C. The value of x is stored in the variable name, and is the value of the assignment. name is usually a bareword (not $name); otherwise it is any operand, whose value is the name of the variable: a braced or quoted name, for a qualified name or an array element ("A($i)" = 0), or a variable or function whose value is the name ($ref = 0). The variable is resolved as by set: in a procedure, a name that is not qualified is a local variable (see global, variable and upvar). Assignment groups right-to-left: a = b = 0 sets both variables.

(name, name, ...) = x
Tuple assignment. The target is a list of names, as written for a list (see OPERANDS), whose elements are variable names or nested lists of names. As for =, a name is a bareword or any other operand whose value is the name ("A($i)", {::ns::v}, $ref). Each variable is set to the element of the value of x at the same place, as given by lindex: a missing element gives the empty string, extra elements are ignored. The value of the assignment is the value of x. For instance, ((x0, y0), (x1, y1)) = ($p, $q) sets four variables from two points. A tuple assignment may not be an element of a list or an argument of a function among others, unless it is enclosed in parentheses: (a, b) = 1, 2 is an error, which is written (a, b) = (1, 2).

x ; y
Sequence. x is evaluated, then y, whose value is the value of the sequence, as the comma operator of C. An empty operand, as in x = 1; or 1;;2, has the empty string as its value. A sequence may not be an argument of a function or an element of a list unless it is enclosed in parentheses: max((a = 1; $a), 2), not max(a = 1; $a, 2), and a = 1; ($a, 2), not a = 1; $a, 2.

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.

MATH FUNCTIONS

A mathematical function such as sin($x) is replaced with a call to an ordinary Tcl command in the ::tcl::mathfunc namespace. The evaluation of an expression such as

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.

TYPES, OVERFLOW, AND PRECISION

Internal floating-point computations are performed using the double C type. When converting a string to floating-point value, exponent overflow is detected and results in the double value of Inf or -Inf as appropriate. Floating-point overflow and underflow are detected to the degree supported by the hardware, which is generally fairly reliable.

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.

PERFORMANCE CONSIDERATIONS

Where an expression contains syntax that Tcl would otherwise perform substitutions on, enclosing an expression in braces or otherwise quoting it so that it's a static value allows the Tcl compiler to generate bytecode for the expression, resulting in better speed and smaller storage requirements. This also avoids issues that can arise if Tcl is allowed to perform substitution on the value before expr is called.

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.

EXAMPLES

A numeric comparison whose result is 1:

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()) }]

SEE ALSO

array, for, if, mathfunc, mathop, namespace, proc, string, Tcl, while

KEYWORDS

arithmetic, boolean, compare, expression, fuzzy comparison, integer value
Copyright © 1993 The Regents of the University of California.
Copyright © 1994-2000 Sun Microsystems, Inc.
Copyright © 2005 Kevin B. Kenny <kennykb(at)acm.org>. All rights reserved

NAME

subst — Perform backslash, command, expression, and variable substitutions

SYNOPSIS

subst ?-nobackslashes? ?-nocommands? ?-noexpr? ?-novariables? string
subst ?-backslashes? ?-commands? ?-expr? ?-variables? string

DESCRIPTION

This command performs variable substitutions, command substitutions, expression substitutions and backslash substitutions on its string argument and returns the fully-substituted result. The substitutions are performed in exactly the same way as for Tcl commands. As a result, the string argument is actually substituted twice, once by the Tcl parser in the usual fashion for Tcl commands, and again by the subst command.

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.

EXAMPLES

When it performs its substitutions, subst does not give any special treatment to double quotes or curly braces (except within command substitutions) so the script

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”.

SEE ALSO

Tcl, eval, break, continue

KEYWORDS

backslash substitution, command substitution, quoting, substitution, variable substitution
Copyright © 1994 The Regents of the University of California.
Copyright © 1994-1996 Sun Microsystems, Inc.
Copyright © 2001 Donal K. Fellows