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 ...

Get Perl Cookbook 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.