Variable Tracing

Tcl supports the ability to invoke procedures when variables are read or written. This can be useful in regular programming (for example, Tk makes extensive use of tracing) but it is especially useful during debugging.

For example, the following command traces any assignments to the array expect_out.

trace variable expect_out w traceproc

The w argument in the command stands for “write”. The last argument is a procedure which is called whenever the variable is written (i.e., assigned to). Instead of w, you can also put r (read) or u (unset). A variable is unset when the unset command is used or the variable goes out of scope.

All trace procedures must be declared with three parameters. The first parameter is the variable name, the second is the element name (if the variable is an array), and the third is the letter r, w, or u, depending on if the variable is being read, written, or unset.

The usual thing to do with a trace procedure when debugging is to print out the variable. Here is a trace procedure to do that. The procedure prints the variable name followed by the value. The type argument is ignored since it will always be w in this example.

proc traceproc {array element type} {
    upvar [set array]($element) var
    puts "new value of [set array]($element) is $var"
}

The trace procedure executes in the context of the scope in which the variable was accessed, so the upvar command is necessary. It gets the variable from the caller’s scope, where it is meaningful.

The array name ...

Get Exploring Expect now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.