| Previous | Next
Tracing Perl/Tk VariablesThis is something of an oddball topic for this Anatomy lesson, but it introduces background information we'll use later. Plus, it lets us do some neat things. The Perl way to trace (or set watchpoints upon) a variable is by using the built-in First we need to define three new commands, the analogs of the Tcl/Tk Trace commands. They are Figure 15-5. Animating a meterThe dial is actually a fat Canvas line item with an arrow on one end. The Scale goes from 0 to 100, with the dial pointing straight up when it reads 50. The Scale's value is updated in the variable my $c = $mw->Canvas(qw/-width 200 -height 110 -bd 2 -relief sunken/)->grid; $c->createLine(qw/ 100 100 10 100 -tag meter -arrow last -width 5/); my $s = $mw->Scale(qw/-orient h -from 0 -to 100 -variable/ => \my $v)->grid; $mw->Label(-text => 'Slide Me for > 5 Seconds')->grid; The idea is to define a callback that's invoked whenever the Scale's variable Here we call $mw->traceVariable(\$v, 'w' => [\&update_meter, $c, $s]); This code demonstrates the other Trace commands. After five seconds, we display trace information, then delete the trace. Once the trace is cleared, the dial stops moving. (This explains why the Scale's value does not correspond to the dial position in Figure 15-5.)
Here's the output from Untrace time ... Watch info : variable : SCALAR(0x82a5178) debug : '0' shadow : '1' value : '56' destroy : ARRAY(0x82fd14c) fetch : ARRAY(0x82fd224) store : ARRAY(0x82fd110)
$_[0] = undef for a scalar, index/key for array/hash $_[1] = variable's current (read), new (write), final (undef) value $_[2] = operation (r, w, or u) $_[3 .. $#_] = optional user callback arguments In our case, the fourth and fifth arguments are the Canvas and Scale widget references, respectively. A Trace callback is responsible for returning the traced variable's new value, so you can choose to keep the proper value or change it. Our callback just needs to peek at the value to adjust the dial, so it keeps the value unchanged. The callback first checks the operation code and returns if the variable is being destroyed. Otherwise, it computes the dial's new position and redraws it.
The Trace module is not a mega-widget. It's a plain old Exporter module, and a tad complicated at that. For the complete listing, see Appendix C, "Complete Program Listings". Trace is a wrapper around Tie::Watch, giving us a super-simple interface, at the expense of some loss of functionality. Let's see what Tie::Watch gives us, since we'll be using it in the future. Tie::WatchTie::Watch is an object-oriented interface to Perl's built-in
The only required argument is
These callbacks return the variable's new value by calling the underlying
Tie::Watch can also watch arrays and hashes, but watching scalars is sufficient for our current needs. |