Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

syntax for quick conditional test in tcl 1

Status
Not open for further replies.

marsd

IS-IT--Management
Apr 25, 2001
2,218
US
What is the syntax for the tcl equivalent
of the c like conditional test:
s = (s < 9) ? 9 : s

I know you use [expr], but I cannot find an example.

Thanks
MMD
 
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:

Code:
if {$s < 9} {set s 9}

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 &quot;Thank you for your purchase of $num &quot;

append msg [expr {($num > 1) ? &quot;geese&quot; : &quot;goose&quot;}]

versus:

Code:
set msg &quot;Thank you for your purchase of $num &quot;

if {$num > 1} {
    append msg &quot;geese&quot;
} else {
    append msg &quot;goose&quot;
}

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
 
Thanks, avia. Very helpful.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top