Main Content

Tcl - using [] or {} for conditions in an if (and while)

Archive - Originally posted on "The Horse's Mouth" - 2007-10-23 05:52:17 - Graham Ellis

In Tcl, the use of square brackets tells the interpreter to "do this first" whereas curly braces are a request to defer execution of a block - perhaps suppressing it completely as in the action on an if statement.

So the if statement's action will NEVER be written in square brackets - [ ] - as that would cause it to be performed irrespective of the actual condition and would defeat the whole purpose of the condition! But it's a different matter with the condition itself. Have a look at this code:

set cost [gets stdin]
 
if [expr $cost > 20] {
    set gpt [expr $cost * 0.9]
    puts "Group ticket at $gpt"
 }
if {$cost > 20} {
    set gpt [expr $cost * 0.9]
    puts "Group ticket at $gpt"
 }
if {[expr $cost > 20]} {
    set gpt [expr $cost * 0.9]
    puts "Group ticket at $gpt"
 }


All three statements produce the same end result, but they do it differently.

The first - using [ ] - evaluates the expression before it ever runs the if comment, to which is passed just a true or false value and not the condition itself. This works well for an if but should never be used in a while, since the condition would never be rechecked and you would have an infinite loop.

The second - using { } - passes the string containing into if which assumes an expr command is to be used to evaluate it. You would usually want it to be expr-ed, so most of the time thats a good and fair assumption.

Using { } and the [ ] with it gives you the deferred block that you'll need when giving a condition for the while, but then also gives you the ability to embed any command - not JUST an expr - with it. And this is the structure you'll need to use for more complex while loops.