How do I convert/cast a string into a bool in Tcl?

boolean, casting, string, tcl

Solution

After thinking some more, and looking some more, the answer probably should be: "It depends"

With my perl background I was expecting something similar to perl. My fault.

In Tcl `string is true` seems to be the official cast function. Valid strings for casting are defined here:

If string is any of 0, false, no, or off, then Tcl_GetBoolean stores a zero value at *boolPtr. If string is any of 1, true, yes, or on, then 1 is stored at *boolPtr. Any of these values may be abbreviated, and upper-case spellings are also acceptable

In my case, I don't care about the string's content so I can just

if {[string length [some_func $some_args]] > 0} {
  ...
}

Another way to write this also is much simpler:

if {[some_func $some_args] != {}} {
  ...
}

Problem

I was expecting ``` if {[some_func $some_args]} { .... } ``` to eval true and simply work as soon as `some_func` returns some string. However there are errors. Learning it the hard way, Tcl accepts only the - empty string -> False - 0 -> False - false -> False - true -> True - 1 -> True To be precise: ``` % expr 1 1 % expr 0 0 % expr wrong # args: should be "expr arg ?arg ...?" % expr {{}} % expr true true % expr false false % expr True syntax error in expression "True": variable references require preceding $ % expr False syntax error in expression "False": variable references require preceding $ ``` It seems `expr` does not normalize it's return value. Note especially the empty string result if an empty string is given. So how do I easily convert strings into booleans?

Original source