The exact Tcl equivalent of the line above would be:
Code:
set s [expr { ($s < 9) ? 9 : $s }]
Thanks to the order of operator precedence, the parentheses are actually optional in this case, but I prefer to include them for clarity.
Actually, for greatest clarity I usually go ahead and use an explicit
if test:
There are some cases where the comparison operator is clearer or more succinct than an explicit
if, but not many. One quick example that comes to mind:
Code:
set msg "Thank you for your purchase of $num "
append msg [expr {($num > 1) ? "geese" : "goose"}]
versus:
Code:
set msg "Thank you for your purchase of $num "
if {$num > 1} {
append msg "geese"
} else {
append msg "goose"
}
However, considering that many of the programmers I've encountered aren't even aware of the comparison operator, I avoid it out of habit to prevent confusion in those who might maintain my code. But that's just my personal preference.
The comparison operator in Tcl isn't even more efficient than an explicit
if test, as these results show:
Code:
proc test1 {s} {
set s [expr { ($s < 9) ? 9 : $s }]
}
proc test2 {s} {
if {$s < 9} {set s 9}
}
[tt]%
[ignore]time { test1 [expr {round(100*rand())}] } 100000[/ignore]
6 microseconds per iteration
%
[ignore]time { test2 [expr {round(100*rand())}] } 100000[/ignore]
5 microseconds per iteration[/tt] - Ken Jones, President
Avia Training and Consulting
866-TCL-HELP (866-825-4357) US Toll free
415-643-8692 Voice
415-643-8697 Fax