Version 12 of string compare ...

Updated 2011-05-08 03:39:08 by RLE

I've no idea why someone thought this page might be useful... RS thinks that in some page [string compare ...] was written with single brackets, which open a potential new page if somebody clicks on the blue brackets. But now that we have this page, comparing strings can be done in various ways:

 if {$name=="foo"} {...}                  ;# (1)
 if {$name eq "foo"} {...}                ;# (2)
 if {[string compare $name foo]==0} {...} ;# (3)
 if {[string equal $name foo]} {...}      ;# (4)
 if {[string match foo $name]} {...}      ;# (5)

(1) is the classic overloading of comparison operators in expr to work also on non-numeric strings, but first tries numeric, including the various number bases, so

 8 == 010
 0xF == 15 == 017

(2) is new string comparison operators from 8.4 or so

(3) used to be recommended, but is so wordy...

(4) is recommended since 8.3 or so

(5) degenerates to 'equal' if the first argument (pattern) does not contain glob meta characters.

Note that string compare is preferred over the == or != if there is a chance that the data could be interpreted as numerics.

Note that string literals must be quoted in (1) and (2).

AMG: Here's another method that lets you compare multiple strings at the same time: if {$name in {foo foo2 foo3}} {...}. In Tcl 8.5 and older, use [lsearch -exact {foo foo2 foo3} $name]. [regexp] also works: [regexp {^foo$|^foo2$|^foo3$} $str].