Chapter 9. Tie
Give me a wild tie brother, One with a cosmic urge, A tie that will swear and rip and tear, When it sees my old blue serge.
The Ties That Bind
Normally,
when you read or update a scalar, array, hash, or filehandle, Perl
performs the appropriate operation on the corresponding internal data
structure. Alternatively, you can use the tie
keyword to bind the value (or variable) to a user-defined object, so
that when you read from or write to that variable, Perl simply calls
a specific method of the object it is tied to. In other words, while
it provides the implementation for a “normal” variable,
Perl expects a user-defined module to do so for a tied variable. Once
a variable is tied, even accesses from the C API of the Perl library
are delegated to the corresponding tied object.
This approach may seem like syntactic sugar, but as you’ll see from the examples in this chapter, it is the syntax that gives it its power: an ordinary variable can be made to invoke a user-defined function whenever a variable is manipulated, without the user’s code changing or being necessarily aware of the subterfuge. The most common use of this technique is to tie a hash variable to a module that can manipulate DBM files, which are typically disk-based hash tables (they can also be BTrees). This technique allows you to make a hash value persistent and is capable of storing much more information than can fit into available memory, while giving the impression that you are manipulating ...
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.