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: Bryan Oakley <oakley@bardo.clearlight.com>
Date: Wed Mar 08 2006 - 18:43:02 CET

Andrew Falanga wrote:
> Bryan Oakley wrote:
>
>>Andrew Falanga wrote:
>>
>>>Hi,
>>>
>>>I have a situation where I'm trying to pass the comparison operator
>>>dynamically to a conditional. Something like this,
>>>...
>>>when this executes, I get this error.
>>>
>>>syntax error in expression " $val1 $oper $val2 ": extra tokens at end of
>>>expression
>>>
>>>So, how would I make this happen?
>>
>>One way is this:
>>
>> if "\$val1 $oper \$val2" {
>>
>>
>
>
> Bryan,
>
> Thanks. Your respons leaves the possibility that there are other ways
> to accomplish this. What would they be?
>

Use your imagination. This is just a simple quoting problem (*). The
"if" command is documented to take an expression as its first argument.
You can build up that expression any way you see fit. Most people
hard-code it inside {}'s, but you can use double quotes, backslashes,
list, format, call a proc, etc.

Remember: quoting is a tool, not a rule. There's no rule that says an if
statement is "if {<expression>} ...". Look at the if man page and you'll
see nowhere is it written that curly braces are required. Under normal
circumstances it is best to use curly braces but you're not required to
do so.

* well, not entirely simple since expr does its own round of
substitution... but it still boils down to quoting rather than some
mystical edge case or hidden feature of the "if" command.

-- 
Bryan Oakley
http://www.tclscripting.com
Received on Sun Apr 30 02:27:50 2006