Forum OpenACS Development: Re: Language lawyering

Collapse
4: Re: Language lawyering (response to 1)
Posted by Don Baccus on
I don't think it's bad style at all ... it is clear that "if" is intended to be used without the explicit call to "expr".

From the Tcl doc:

The if command evaluates expr1 as an expression (in the same way that expr evaluates its argument).
Collapse
6: Re: Language lawyering (response to 4)
Posted by Alfred Werner on
Welcome back Don. That explains it for me - I missed that line in the TCL docs.

I was really looking to see how many cases of

if {$somestring == 'some literal' }  were in the code and that was just a surprise to me.

Seems like the following things happen with some regularity:

$somestring == 'some literal'  happens quite a bit and could be cleaned up pretty easily

There seems to be some confusion / debate over whether

$somestring eq 'some literal'
[string equal $somestring 'some literal']
[string compare $somestring 'some literal']

are equivalent.

FAIK, [string compare] and eq have been around for ages - [string equal] was JUST introduced.

[string equal] does EXACTLY the same thing as eq - compares two STRINGS. The reason for introducing [string equal] when eq already exists is to allow the other [string] parameters to come into play, and also because eq only exists within the context of an [expr] construct, which as you pointed out is implicitly invoked in an if statement (and is the reason I always assumed it was a first order operator, rather than only existing within the expr context).

[string compare] thinks of the two operands as less,equal, or greater,
[string equal] and eq only says whether they are identical strings. If you want to be case insensitive, both [string equal] and [string compare] have the -nocase option.

I had always missed the following:
if {$a eq $b}
is implicitly if [expr {$a eq $b}]
I wrongly assumed it was made to be [expr $a eq $b] - which just doesn't work in the TCL interpreter.

So back to looking at the 'things to look out for' threads and pages:
$somestring eq 'some literal' vs $somestring == 'some literal'.

Those will NOT return a bad result if the literal can not be interpreted as a number. The worst case there is that the interpreter always tries them as a number first, so they are more inefficient because the literal will always be a string. The only time it may be actually WRONG to use the == is if both arguments are variables that the author intends/expects to be strings, but may conceivably be numbers during some invocation.