Debugging Tcl script with puts

Using puts is the one of the oldest, yet effective debugging technique. For example:

puts "before calling myproc"
puts "myvar = $myvar"
myproc myvar
puts "after calling myproc"
puts "myvar = $myvar"

This technique is good, but it has at least two problems:

  1. To turn off debugging output, I either have to delete or comment out tens if not hundreds of puts lines like those above. To turn them back on, I have to reverse the process for that many lines.
  2. This is not a problem, but I found myself using puts to display value of a variable quite often, therefore it would be nice if I can streamline that process

To answer both questions, I created the following code snippet which I paste at the beginning of my script:

# Output debug only when the user set the environment variable
# DEBUG=1. In Bash:
#     $ export DEBUG=1
# In csh and tclsh:
#     # setenv DEBUG 1
if {[info exists env(DEBUG)] && $env(DEBUG)} {
    proc dbg {msg} { puts $msg }
    proc dbgVar {varName} {
        upvar 1 $varName varValue
        dbg "$varName = '$varValue'"
} else {
    proc dbg {msg} {}
    proc dbgVar {varName} {}

Now, the original block of code would become:

dbg "before calling myproc"
dbg "myvar = $myvar"
myproc myvar; # Now call myproc, which modifies myvar
dbg "after calling myproc"
dbgVar myvar

Here is the instruction for turning debuggin on or off:

	$ export DEBUG=1 # Debug on  for sh and bash
	$ unset DEBUG    # Debug off for sh and bash
	# setenv DEBUG 1 # Debug on  for csh and tcsh
	# unsetenv DEBUG # Debug off for csh and tcsh 

Now, I don’t have to go over my code to comment or uncomment lines after lines of code to turn on/off debugging output. I also have at my disposal a simple way to display the value of a variable. Life is good.

In the future, I will probably put this snippet into a package to further streamline the process.

One thought on “Debugging Tcl script with puts

  1. Hae

    I often use puts to. But the drawback is, that for the release code you would have to comment the ‘puts’ or delete it.
    A while ago I discovered the logger package in tcllib. This provides an easy means to leave the debug code in the release version and to turn it on anytime. It also has different levels of information that can be printed.

    In Tcl/Tk tools I write for my actual work I can bring up the console window on a and see the output of the logger.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s