Perl version 5.10.0 documentation - perltiePage 1http://perldoc.perl.org
perltie - how to hide an object class in a simple variable
tie VARIABLE, CLASSNAME, LIST$object = tied VARIABLEuntie VARIABLE
Prior to release 5.0 of Perl, a programmer could use dbmopen()to connect an on-disk database in thestandard Unix dbm(3x)format magically to a %HASH in their program. However, their Perl was eitherbuilt with one particular dbm library or another, but not both, andyou couldn't extend this mechanismto other packages or types of variables.Now you can.The tie() function binds a variable to a class (package) that will providethe implementation for accessmethods for that variable. Once this magichas been performed, accessing a tied variableautomatically triggersmethod calls in the proper class. The complexity of the class ishidden behindmagic methods calls. The method names are in ALL CAPS,which is a convention that Perl uses toindicate that they're calledimplicitly rather than explicitly--just like the BEGIN() and END()functions.In the tie() call,
is the name of the variable to beenchanted.
is the name of aclass implementing objects ofthe correct type. Any additional arguments in the
are passed tothe appropriate constructor method for that class--meaning TIESCALAR(),TIEARRAY(), TIEHASH(),or TIEHANDLE(). (Typically these are argumentssuch as might be passed to the dbminit() function ofC.) The objectreturned by the "new" method is also returned by the tie() function,which would beuseful if you wanted to access other methods in
. (You don't actually have to return areference to a right"type" (e.g., HASH or
) so long as it's a properly blessedobject.) Youcan also retrieve a reference to the underlying objectusing the tied() function.Unlike dbmopen(), the tie() function will not
a modulefor you--you need to do thatexplicitly yourself.
A class implementing a tied scalar should define the following methods:TIESCALAR, FETCH,STORE, and possibly UNTIE and/or DESTROY.Let's look at each in turn, using as an example a tie class forscalars that allows the user to dosomething like:
tie $his_speed, 'Nice', getppid();tie $my_speed, 'Nice', $$;
And now whenever either of those variables is accessed, its currentsystem priority is retrieved andreturned. If those variables are set,then the process's priority is changed!We'll use Jarkko Hietaniemi <
>'s BSD::Resource class (notincluded) to access thePRIO_PROCESS, PRIO_MIN, and PRIO_MAX constantsfrom your system, as well as thegetpriority() and setpriority() systemcalls. Here's the preamble of the class.
package Nice;use Carp;use BSD::Resource;use strict;