|Perl Language Reference Manual|
by Larry Wall and others
Paperback (6"x9"), 724 pages
RRP £29.95 ($39.95)
Sales of this book support The Perl Foundation! Get a printed copy>>>
18 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
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
require a module
for you--you need to do that explicitly yourself.
|ISBN 9781906966027||Perl Language Reference Manual||See the print edition|