Re: How to dynamically pass operators to if?
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.tcl archive

Re: How to dynamically pass operators to if?

From: Donald Arseneau <asnd@triumf.ca>
Date: Thu Mar 09 2006 - 03:04:36 CET

Andrew Falanga <not_real@hp.com> writes:

> I have a situation where I'm trying to pass the comparison operator
> dynamically to a conditional. Something like this,

> if { $val1 $oper $val2 } {

This used to work, long ago, but the round of expansion done by
[expr] (and its equivalents) was changed to perform substitution
of operands only, not operations or other syntax. That's for
processing efficiency. When you need more than values in variables
you can let the command parser do the expansion by quoting with
quotes instead of braces

    if "$val1 $oper $val2" {

which might be just what you want, if this is not a performance
bottleneck.

However, the performance optimization in expr is significant, and
you will do better to avoid extra expansion. One minor improvement
is

    if "\$val1 $oper \$val2" {

but you will do much better by testing within the expression syntax
rather than passing parts of the syntax as strings

    if { $oper == ">" ? $val1 > $val2 : $val1 < $val2 } {

(But better to use a boolean flag rather than a string).

(wishing) 4 % time {expr "$val1 $oper $val2" } 10000
8.6735 microseconds per iteration
(wishing) 5 % time {expr "\$val1 $oper \$val2" } 10000
6.2237 microseconds per iteration
(wishing) 6 % time {expr "$val1 > $val2" } 10000
8.2399 microseconds per iteration
(wishing) 7 % time {expr {$val1 > $val2} } 10000
0.9003 microseconds per iteration
(wishing) 8 % time {expr {$oper==">"?$val1 > $val2 : $val1<$val2} } 10000
1.9421 microseconds per iteration

 

-- 
Donald Arseneau                          asnd@triumf.ca
Received on Sun Apr 30 02:28:06 2006