Example: Monitoring Variables
tie
makes it really convenient to
monitor a variable. In this section, we will develop a module called
Monitor.pm that prints out a message on STDERR
whenever a variable of your choice is accessed. [34]
use Monitor; monitor(\$x, 'x'); monitor(\%y, 'y');
Whenever $x
or %y
is changed,
this module prints out something like this on
STDERR
:
Wrote : $x ... 10 Read : $x ... 10 Died : $x Wrote : $y{a} ... 1 Cleared : %y
This module is useful while debugging, where it is not clear at what
point a certain variable is changing, especially when it changes
indirectly through a reference. This module can be enhanced to
support watch expressions such as print
'ahhh'
when
$array[5]
>
10
. Given Perl’s support for
eval
, this is a reasonably simple task.
monitor
takes a variable by reference and a name
to be used when it prints out its messages. The first parameter is
used to do a tie
on the variable.
tie
has the unfortunate property that it hides the
original value held by the variable. (The value is restored upon
untie
.) Clearly, we don’t want
Heisenberg’s Uncertainty Principle to creep in here—our
act of monitoring should not affect the user’s view of that
variable. For this reason, we store away the original value as an
attribute of the tied object and have FETCH
and
STORE
use this copy. Finally, when we are not
interested in the variable any more, we use
unmonitor
, which calls untie
internally.
Monitor, shown in Example 9.3, delegates responsibility to a nested ...
Get Advanced Perl Programming 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.