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.
(written 2007-10-23 05:52:17)
Associated topics are indexed under
T203 - Tcl/Tk - Conditionals and Loops
Some other Articles
Sorting in Tcl - lists and arraysTcl - global, upvar and uplevel.Square Bracket protection in TclTcl - append v lappend v concatTcl - using [] or {} for conditions in an if (and while)Dark DawnPictures FramedSomeone else's weddingPerl - progress bar, supressing ^C and coping with huge data flowsUsing PHP to upload images / Store on MySQL database - security questions