now I have to maintain older tcl source and I found a lot of "if"
constructs with non-braced expressions, like this:
if [info exists $varName] {
...
}
I would write the "if" this way:
if {[info exists $varName]} {
...
}
Is there a need to go through the old sources and to change the non-
braced into braced if-expressions?
If it is only about speed, runtime behaviour, than I don't think, that
I will invest time in this.
Thanks in advance for any comment!
Best regards,
Martin Lemburg
Siemens Automation and Drives - UGS PLM Software
The first argument of if, while, and expr, undergoes an extra
substitution step.
There's a good reason: noncommutative ops like && and ||, allowing to
write
if {[foo]||[bar]} {...}
and making sure that only [foo] is executed if it returns true. If
instead you write
if [foo]||[bar] {...}
then clearly both are executed before any boolean operation can take
place: too bad if [bar] raises an exception in that case.
A corollary is that if your legacy code contains
if [f] {...}
and the result of [f] contains [] or $, then the second substitution
will be non-negligible.
If this was the intended behavior, then of course you mustn't brace
the argument.
But in the example you gave, [info exists ...], the possible results 0
and 1 are constants, so there's no risk.
On the other hand, there's no strong need either. A filesystem hit
like [info exists] is most likely much more expensive than the extra
substitution and loss of bytecode compilation caused by the lack of
braces.
> If it is only about speed, runtime behaviour, than I don't think, that
> I will invest time in this.
If you only have [info exist]s, don't.
If things are trickier, you might consider doing it automatically.
It will be an interesting exercise demonstrating the introspective
power of Tcl ! (hint: use [regexp] and [info complete])
-Alex
I'm not the only maintainer, so I needed such good explaination to let
my colleagues see the same "to do and to don't"s.
Most of the non-braced if conditions are really not dangerous, because
e.g. of the usage of "info exists". But I found some while and for
loops too, even if there was no need to build dynamic/runtime
dependent conditions.
So ... we'll invest some time.
Thanks again!
Best regards,
Martin Lemburg
Siemens Automation and Drives - UGS PLM Software
On May 14, 7:40 pm, Alexandre Ferrieux <alexandre.ferri...@gmail.com>
wrote:
Of course, I forgot to mention, [while] and [for] are much more
candidates for bracing since they evaluate the expression several
times. So it's a good idea to clean this up anyway !
-Alex