You want to add special processing to a variable or handle.
tie function to give your ordinary
variables object hooks.
Anyone who’s ever used a DBM file under Perl has already used
tied objects. Perhaps the most excellent way of using objects is such
that the user never notices them. With
can bind a variable or handle to a class, after which all access to
the tied variable or handle is transparently intercepted by specially
named object methods.
The most important
tie methods are
FETCH to intercept
read access, STORE
to intercept write access, and the constructor, which is one of
TIESCALAR, TIEARRAY, TIEHASH, or
tie $s, "SomeClass"
$p = $s
$p = $obj->FETCH()
$s = 10
Where did that
$obj come from? The
tie triggers a call to the class’s TIESCALAR
constructor method. Perl squirrels away the object returned and
surreptitiously uses it for later access.
Here’s a simple example of a
tie class that
implements a value ring. Every time the variable is read from, the
next value on the ring is displayed. When it’s written to, a
new value is pushed on the ring. Here’s an example:
#!/usr/bin/perl # demo_valuering - show tie class use ValueRing; tie $color, 'ValueRing', qw(red blue); print "$color $color $color $color $color $color\n";
$color = 'green'; print "$color $color $color $color $color $color\n";
red blue red blue red blue
green red ...