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:
- 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.
- 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.
