the if statement in TCL

前端 未结 4 788
忘掉有多难
忘掉有多难 2021-02-04 06:26

I have a question about if statement in tcl of the following code:

if {(($number == 1)&&($name == \"hello\")) || (($number == 0)&&($name == \"yes         


        
4条回答
  •  春和景丽
    2021-02-04 06:51

    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.

    The Specifics

    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.

    Warning: Advanced Topic

    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! I mean it. It's a very advanced technique that you hardly ever need, and there's often a better way to do your overall goal. If you think you might need it, for goodness' sake ask here on SO and we'll try to find a better way; there's almost always one available.

提交回复
热议问题