I have a question about if statement in tcl of the following code:
if {(($number == 1)&&($name == "hello")) || (($number == 0)&&($name == "yes"))} {
#do something here
}
The above code works, but if I wrote it down like this:
if {{$number == 1 && $name == "hello"} || {$number == 0&&$name == "yes"}} {
#do something here
}
It complains that the $number
is expected to be a boolean, why? Is the second one not a valid expression? How to correct it?
Braces, {}
, and parentheses, ()
, are not interchangeable in Tcl.
Formally, braces are (with one exception) a kind of quoting that indicates that no further substitutions are to be performed on the contents. In the first case above, this means that that argument is delivered to if
without substitution, which evaluates it as an expression. The expression sub-language has a strongly-analogous brace interpretation scheme to general Tcl; they denote a literal value with no further substitutions to perform on it.
By contrast, parentheses are mostly not special in Tcl. The exceptions are in the names of elements of arrays (e.g., $foo(bar)
), in the expression sublanguage (which uses them for grouping, as in mathematical expressions all over programming) and in the regular expression sublanguage (where they are a different type of grouping and a few other things). It is entirely legal to use parentheses — balanced or otherwise — as part of a command name in Tcl, but you might have your fellow programmers complaining at you anyway for writing confusing code.
In this specific case, the test expression of this if
:
if {{$number == 1 && $name == "hello"} || {$number == 0&&$name == "yes"}} {...}
is parsed into:
blah#1 LOGICAL_OR blah#2
where each blah
is a literal. Unfortunately, blah#1
(which is exactly equal to $number == 1 && $name == "hello"
) has no boolean interpretation. (Nor does blah#2
but we never bother to consider that.) Things are definitely going very wrong here!
The simplest fix is to change those bogus braces back to parentheses:
if {($number == 1 && $name == "hello") || ($number == 0&&$name == "yes")} {...}
I bet this is what you originally wanted.
However, the other fix is to add in a little extra:
if {[expr {$number == 1 && $name == "hello"}] || [expr {$number == 0&&$name == "yes"}]} {...}
This is normally not a good idea — extra bulk for no extra gain — but it makes sense where you're trying to use a dynamically-generated expression as a test condition. Do not do this unless you're really really certain you need to do this!