Boolean and the comparision operators '''==''' and '''!='''
HaO 2011-05-02 Comparisions with == or != do not work with booleans not in canonical form:
% expr {true == 1}
0This issue may be avoided using the bool() function to bring strings in boolean canonical form:% expr {bool(true) == bool(1)}
1This is only recommeded if two variables contain boolean data.expr {bool($b1) == bool($b2)}otherwise, one would use:expr { $b1 }
expr { ! $b1 }MG The string is command also recognises booleans:
proc trueorfalse {str} {
if { ![string is boolean -strict $str] } {
return -1; # not a boolean
}
return [string is true $str]
}
% trueorfalse foo
-1
% trueorfalse yes
1
% trueorfalse off
0HaO Yes, correct, another way to get a value in canonical boolean form is:string is true -strict $b
hv Here is my little script which lists which token is true, false, or neither:
#
# Which token is considered true/false?
#
set tokens {-2 -1 0 1 2 yes no Yes No YES NO on off On Off ON OFF
true false True False TRUE FALSE Y N OK FAIL}
set trueTokens {}
set falseTokens {}
set neitherTokens {}
foreach token $tokens {
if {[string is true -strict $token]} {
lappend trueTokens $token
} else {
if {[string is false -strict $token]} {
lappend falseTokens $token
} else {
lappend neitherTokens $token
}
}
}
puts "True: $trueTokens"
puts "False: $falseTokens"
puts "Neither: $neitherTokens"Output:
True: 1 yes Yes YES on On ON true True TRUE Y
False:0 no No NO off Off OFF false False FALSE N
Neither: -2 -1 2 OK FAILAMG: Why does [string is boolean] reject "2" when it valid to use "2" anywhere a Boolean is expected?Also, in addition to the strings tested above by HV's code, [string is boolean] accepts all capitalizations of: t, tr, tru, f, fa, fal, fals, ye, and of. Notably, o is not accepted, since it is a common prefix shared by on and off.
