O'Reilly logo

Perl Cookbook by Nathan Torkington, Tom Christiansen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Creating Magic Variables with tie

Problem

You want to add special processing to a variable or handle.

Solution

Use the tie function to give your ordinary variables object hooks.

Discussion

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 tie, you 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 TIEHANDLE.

User Code

Executed Code

tie $s, "SomeClass"
SomeClass->TIESCALAR()
$p = $s
$p = $obj->FETCH()
$s = 10
$obj->STORE(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";

                  red blue red blue red blue

$color = 'green';
print "$color $color $color $color $color $color\n";

                  green red ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required