Boolean logic in Tcl

Many people who write Tcl script get confused when it comes to boolean logic, especially within if, while construct. To clear up some of these confusions, let’s take a look at the following interactive session:

	(tcl) 66 % # What is true?
	(tcl) 66 % set var -1
	(tcl) 67 % string is true $var
	(tcl) 68 % # So, -1 is not considered a token for true. Let see now:
	(tcl) 68 % if {$var} {puts "$var is true"}
	-1 is true
	(tcl) 69 % # It seems the expression in the if statement only care if var is zero or not
	(tcl) 69 % # Try a couple of other tokens:
	(tcl) 69 % string is true yes
	(tcl) 70 % string is true no
	(tcl) 71 % string is false no
	(tcl) 72 % # So yes=true, no=false, so far so good
	(tcl) 72 % set var yes
	(tcl) 73 % if {$var} {puts "$var is true"}
	yes is true
	(tcl) 74 % set var neither
	(tcl) 75 % if {$var} {puts "$var is true"}
	expected boolean value but got "neither"
	(tcl) 76 % # Now that is the behavior I expected
	(tcl) 76 % set var no
	(tcl) 77 % if {!$var} {puts "$var is false"}
	no is false
	(tcl) 78 % # Worked as expected
	(tcl) 78 %

Normally, Tcl defines true as 1 and false as 0, but as line 68 shows, Tcl considers any non-zero numerical value as true, not just 1.

Lines 69-77: Tcl’s boolean vocabulary also extends to other tokens such as true/false, y/n, yes/no, and on/off. These tokens are case insensitive, which means Yes, yes, and YES are the same.

Line 74-75: If Tcl does not understand a token, it will flag as an error.

Here are the summary points:

  1. For numeric values 0=false and non-zero=true
  2. For non numeric values, Tcl understands true/false, yes/no, y/n, and on/off. The language might understand more tokens than that, but those are the ones I tested.
  3. Anything other than 1 and 2 will raise an error

3 thoughts on “Boolean logic in Tcl

  1. Tarun Khanna


    spawn telnet

    expect login*
    send “admin\r”

    expect Password*
    send “abcdef123\r”

    expect “Router#”
    send “exit\r”

    I want the above code to run in a loop such that script keeps doing a telnet to the device. Please suggest


  2. Hai Post author

    Do this:

    while 1 {
    # Your code here

    In general, please visit or comp.lang.tcl, you are more likely to get answers there.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s