Tying Scalars

To implement a tied scalar, a class must define the following methods: TIESCALAR, FETCH, and STORE (and possibly UNTIE and DESTROY). When you tie a scalar variable, Perl calls TIESCALAR. When you read the tied variable, it calls FETCH, and when you assign a value to the variable, it calls STORE. If you’ve kept the object returned by the initial tie (or if you retrieve it later using tied), you can access the underlying object yourself—this does not trigger its FETCH or STORE methods. As an object it’s not magical at all, but rather quite objective.

Perl calls UNTIE, if you’ve defined it, when it unties the variable. This gives you a chance to do any bookkeeping or clean-up before the association disappears and the variable is no longer special.

If a DESTROY method exists, Perl invokes it when the last reference to the tied object disappears, just as for any other object. That happens when your program ends or when you call untie, which eliminates the reference used by the tie. However, untie doesn’t eliminate any outstanding references you might have stored elsewhere; DESTROY is deferred until those references are gone, too.

The Tie::Scalar and Tie::StdScalar packages, both found in the standard Tie::Scalar module, provide some simple base class definitions if you don’t want to define all of these methods yourself. Tie::Scalar provides elemental methods that do very little, and Tie::StdScalar provides methods that make a tied scalar behave like a regular Perl scalar. ...

Get Programming Perl, 4th Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.