More On Expressions

In the while and if command examples, I enclosed the expressions in braces and said that the expressions were evaluated by the commands themselves. For example, in the while command, the expression was

$count > 0

Because the expression was wrapped in braces, evaluation of $count was deferred. During expression evaluation, a $ followed by a variable name is interpreted in just the same way it is done with arguments that are not wrapped in braces. Similarly, brackets are also interpreted the same way in both contexts. For this reason, commands like the following two have the same result. But in the first command, $count is evaluated before expr executes, while in the second command, expr itself evaluates $count.

expr $count > 0
expr {$count > 0}

The expr command can perform some string operations. For example, quoted strings are recognized as string literals. Thus, you can say things like:

expr {$name == "Don"}

Unquoted strings cannot be used as string literals. The following fails:

expr {$name == Don}

Unquoted strings are not permitted inside expressions to prevent ambiguities in interpretation. But strings in expressions can still be tricky. In fact, I recommend avoiding expr for these implicit string operations. The reason is that expr tries to interpret strings as numbers. Only if they are not numbers, are they treated as uninterpreted strings. Consider:

tclsh>if {"0x0" == "0"} {puts equal}
equal

Strings which are not even internally representable as numbers can ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.