Debugging
The rapid turnaround with Tcl coding means that it is often sufficient to add a few puts statements to your script to gain some insight about its behavior. This solution doesn't scale too well, however. A slight improvement is to add a Debug procedure that can have its output controlled better. You can log the information to a file, or turn it off completely. In a Tk application, it is simple to create a text widget to hold the contents of the log so that you can view it from the application. Here is a simple Debug procedure. To enable it you need to set the debug(enable) variable. To have its output go to your terminal, set debug(file) to stderr.
Example 13-12 A Debug procedure
proc Debug { args } {
global debug
if {![info exists debug(enabled)]} {
# Default is to do nothing
return
}
puts $debug(file) [join $args " "]
}
proc DebugOn {{file {}}} {
global debug
set debug(enabled) 1
if {[string length $file] == 0} {
set debug(file) Stderr
} else {
if [catch {open $file w} fileID] {
puts stderr "Cannot open $file: $fileID"
set debug(file) stderr
} else {
puts stderr "Debug info to $file"
set debug(file) $fileID
}
}
}
proc DebugOff {} {
global debug
if {[info exists debug(enabled)]} {
unset debug(enabled)
flush $debug(file)
if {$debug(file) != "stderr" &&
$debug(file) != "stdout"} {
close $debug(file)
unset debug(file)
}
}
}
 |