Search code examples
tclparenthesesbraces

How Tcl parses whitespace within parentheses in an If statement


I understand that the if statement in Tcl requires braces { } instead of parentheses ( ).

However, the following (erroneous) code prints "Aha!" because Tcl seems to be able to interpret the if condition correctly:

set flow_control 1
if ($flow_control==1) {
    puts "Aha!"
}

Yet the following (with spaces) fails with 'unbalanced open paren in expression "(1"'

set flow_control 1
if ($flow_control == 1) {
    puts "Aha!"
}

And of course, using braces either with or without parentheses, with or without spaces works:

set flow_control 1
if {$flow_control == 1} {
    puts "Braces rule!"
}

My question is, why does the second case fail?

Donal Fellows' answer to the if statement in TCL explains clearly the difference between braces and parentheses but I can't figure out why whitespace causes the second block to fail.


Solution

  • Braces are a quoting mechanism that groups several words into a single word. Refer to the 12 syntax rules

    Note carefully the syntax of the if command:

    if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?
    

    expr1 must be a single word.

    { $foo == $bar } is a single word due to the braces

    ($flowcontrol == 1) has no braces or double quotes, so it is parsed as 3 separate words. The first word's variable is expanded and then the word is given to if as the expr1, and (1 is not a valid expression.

    ($flowcontrol==1) without spaces is a single word. The variable is expanded and then (1==1) -- a valid expression -- is given to if.