perltie - how to hide an object class in a simple variable
tie VARIABLE, CLASSNAME, LIST
$object = tied VARIABLE
untie VARIABLE
|
|
Prior to release 5.0 of Perl, a programmer could use dbmopen() to connect an on-disk database
in the standard Unix dbm(3x) format magically to a %HASH in their program. However, their Perl
was either built with one particular dbm library or another, but not both, and you couldn't
extend this mechanism to other packages or types of variables.
Now you can.
The tie() function binds a variable to a class (package) that will provide the implementation
for access methods for that variable. Once this magic has been performed, accessing a tied
variable automatically triggers method calls in the proper class. The complexity of the class is
hidden behind magic methods calls. The method names are in ALL CAPS, which is a convention that
Perl uses to indicate that they're called implicitly rather than explicitly--just like the
BEGIN() and END() functions.
In the tie() call, VARIABLE is the name of the variable to be enchanted. CLASSNAME
is the name of a class implementing objects of the correct type. Any additional arguments in the
LIST are passed to the appropriate constructor method for that class--meaning
TIESCALAR(), TIEARRAY(), TIEHASH(), or TIEHANDLE(). (Typically these are arguments such as might
be passed to the dbminit() function of C.) The object returned by the "new" method is
also returned by the tie() function, which would be useful if you wanted to access other methods
in CLASSNAME. (You don't actually have to return a reference to a right
"type" (e.g., HASH or CLASSNAME) so long as it's a properly blessed
object.) You can also retrieve a reference to the underlying object using the tied() function.
Unlike dbmopen(), the tie() function will not use or require a
module for you--you need to do that explicitly yourself.
See DB_File or Config for some interesting tie()
implementations. A good starting point for many tie() implementations is with one of the modules
Tie::Scalar, Tie::Array, Tie::Hash, or Tie::Handle.
You cannot easily tie a multilevel data structure (such as a hash of hashes) to a dbm file.
The first problem is that all but GDBM and Berkeley DB have size limitations, but beyond that,
you also have problems with how references are to be represented on disk. One experimental
module that does attempt to address this need partially is the MLDBM module. Check your nearest
CPAN site as described in perlmodlib
for source code to MLDBM.
Tied filehandles are still incomplete. sysopen(), truncate(), flock(), fcntl(), stat() and -X
can't currently be trapped.
Tom Christiansen
TIEHANDLE by Sven Verdoolaege <skimo@dns.ufsia.ac.be> and Doug MacEachern <dougm@osf.org>
UNTIE by Nick Ing-Simmons <nick@ing-simmons.net>
Tying Arrays by Casey West <casey@geeknest.com>
|