Reputation: 3255
I have this script:
$ cat tmp/bool.tcl
puts "[expr [expr True] == [expr true] ]"
I expect it prints 1 because both "True" and "true" are boolean true so they should equal, but I get 0:
$ tclsh tmp/bool.tcl
0
Of course this is simplified code. The real code generates boolean values in string, "True", "true", "Yes", "yEs", etc.
Do I have to make them all lower case before comparing them?
I do not understand why the above code does not equal.
Upvotes: 1
Views: 885
Reputation: 137807
The ==
operator is defined to do (the documentation in the expr
page itself is more obscure):
numeric comparison if possible, exact string comparison otherwise
Neither True
nor true
is numeric, so exact string comparison is used. The two values differ in the first character of their string representation; they are therefore not equal in the sense of ==
.
To compare uncontrolled boolean values for equality, invert them first as the result of the !
operator is both boolean and numeric (i.e., it's 0 or 1):
set a Yes
set b tRuE
expr {!$a == !$b}
Upvotes: 1
Reputation: 247240
% puts "[expr [expr True] == [expr true] ]"
0
Let's look at what each side does:
% expr True
True
% expr true
true
So, both recognized as boolean values, but not equal. Let's convert those strings to a "canonical" boolean form:
% set a True
True
% set b true
true
% expr {$a == $b}
0
% expr {!!$a == !!$b}
1
What's going on here: step-by-step
% expr {$a}
True
% expr {!$a}
0
% expr {!!$a}
1
The native "true/false" values are "1/0" respectively. And clearly 1 == 1
Opinion: this feels like it goes back to Tcl's "everything is a string" roots, and the strings "True" and "true" are unequal.
Upvotes: 3