In Tcl, why do I have to use quotes and curly braces for expr's argument when comparing two string literals?

36 Views Asked by At

I wanna compare two literal strings using expr command in Tcl. The correct command is:

expr {"string1" == "string1"}

In my understanding, curly braces in Tcl is used to prevent substitution. But there is no variables in the comparison because I only compare string literals. For another, since words are separated by whitespace in Tcl command, if I don't use space, there is no need to group the math expression into a single word. So, I think I can remove both quotes and curly braces. But I got errors if do that. Specifically, if I remove quotes, the error is:

% expr {string1==string1}

invalid bareword "string1"

in expression "string1==string1";

should be "$string1" or "{string1}" or "string1(...)" or ...

If I remove curly braces, the error is:

% expr "string1"=="string1"

extra characters after close-quote

I don't understand why there are these errors. Can you explain for me? Thank you.

1

There are 1 best solutions below

1
Donal Fellows On

You should (almost) always put braces round an expr expression; they make the semantics simple enough that Tcl can compile the expression ahead of time, giving a very nice speed boost. That locking down of the semantics also makes the code a lot safer.

The syntax of expressions (as described in the manual) requires strings to be in double quotes (substitutes using Tcl rules) or braces (unsubstituted), and always has done. Technically, there are exceptions for boolean literals and a few other things (such as Inf which is a floating point value but not syntactically so in the parser), but they're all explicit exceptions for definite known words.