Home > Articles > Programming > Perl

The Perl Ties That Bind

  • Print
  • + Share This
Learn how to provide reusable code using Perl 5 ties - a way of intercepting accesses to a Perl variable (array, hash, scalar, or filehandle).
From the author of

Introduction

Programmers are used to "modules" as a way of reusing code. Some modules provide subroutines, others provide an object-oriented interface. New in Perl 5 are ties—a way of intercepting accesses to a Perl variable (array, hash, scalar, or filehandle). This article describes how to provide reusable code using ties.

What Is a Tie?

You've probably already met tie-like behavior in the form of dbmopen(). This built-in Perl subroutine associates a Perl hash with a dbm(3)-style file on disk. If you fetch a value from the hash, Perl looks up the corresponding value in the dbm file. If you store a value, Perl stores the value in the dbm file.

The biggest problem with dbmopen() is that the type of dbm file that it uses was decided when your Perl interpreter was compiled. There are many different dbm-like libraries, but dbmopen() only allows you to use one. To solve this inflexibility, Perl 5 introduced tie(), a more general mechanism for hiding complex behavior behind a variable, whether a hash, array, scalar, or filehandle.

Perl keeps an object for each variable you tie(). Each access to the tied variable results in method calls on the object. You can tie() a variable to just about anything: a database, a text file, a directory, even the Windows registry. You can even use tie() to trace accesses to a variable.

The methods automatically called by Perl have special names, which are in CAPS. There are only a few implicitly called methods that your tying class can and should provide, which will be discussed later. The tying class is the invisible glue that holds your variable and resource together.

The example I'll work through is a tie to a hash, since that's the most involved, the longest and best-supported, and (consequently) the most common. By the end of this article, you should have a good understanding of the tie() function, tying classes, and the knowledge to begin writing your own tie() class.

  • + Share This
  • 🔖 Save To Your Account