<P>perltie - how to hide an object class in a simple variable</P>
<P>
<HR>
<H1><A NAME="synopsis">SYNOPSIS</A></H1>
<PRE>
tie VARIABLE, CLASSNAME, LIST</PRE>
<PRE>
$object = tied VARIABLE</PRE>
<PRE>
untie VARIABLE</PRE>
<P>
<HR>
<H1><A NAME="description">DESCRIPTION</A></H1>
<P>Prior to release 5.0 of Perl, a programmer could use <A HREF="../../lib/Pod/perlfunc.html#item_dbmopen"><CODE>dbmopen()</CODE></A>
to connect an on-disk database in the standard Unix <CODE>dbm(3x)</CODE>
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.</P>
<P>Now you can.</P>
<P>The <A HREF="../../lib/Pod/perlfunc.html#item_tie"><CODE>tie()</CODE></A> 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 <CODE>BEGIN()</CODE> and <CODE>END()</CODE>
functions.</P>
<P>In the <A HREF="../../lib/Pod/perlfunc.html#item_tie"><CODE>tie()</CODE></A> call, <CODE>VARIABLE</CODE> is the name of the variable to be
enchanted. <CODE>CLASSNAME</CODE> is the name of a class implementing objects of
the correct type. Any additional arguments in the <A HREF="#item_LIST"><CODE>LIST</CODE></A> 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 <CODE>dbminit()</CODE> function of C.) The object
returned by the ``new'' method is also returned by the <A HREF="../../lib/Pod/perlfunc.html#item_tie"><CODE>tie()</CODE></A> function,
which would be useful if you wanted to access other methods in
<CODE>CLASSNAME</CODE>. (You don't actually have to return a reference to a right
``type'' (e.g., HASH or <CODE>CLASSNAME</CODE>) so long as it's a properly blessed
object.) You can also retrieve a reference to the underlying object
using the <A HREF="../../lib/Pod/perlfunc.html#item_tied"><CODE>tied()</CODE></A> function.</P>
<P>Unlike dbmopen(), the <A HREF="../../lib/Pod/perlfunc.html#item_tie"><CODE>tie()</CODE></A> function will not <A HREF="../../lib/Pod/perlfunc.html#item_use"><CODE>use</CODE></A> or <A HREF="../../lib/Pod/perlfunc.html#item_require"><CODE>require</CODE></A> a module
for you--you need to do that explicitly yourself.</P>
<P>A class implementing a tied scalar should define the following methods:
TIESCALAR, FETCH, STORE, and possibly DESTROY.</P>
<P>Let's look at each in turn, using as an example a tie class for
scalars that allows the user to do something like:</P>
<PRE>
tie $his_speed, 'Nice', getppid();
tie $my_speed, 'Nice', $$;</PRE>
<P>And now whenever either of those variables is accessed, its current
system priority is retrieved and returned. If those variables are set,
then the process's priority is changed!</P>
<P>We'll use Jarkko Hietaniemi <<EM><A HREF="mailto:jhi@iki.fi">jhi@iki.fi</A></EM>>'s BSD::Resource class (not
included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants
from your system, as well as the <A HREF="../../lib/Pod/perlfunc.html#item_getpriority"><CODE>getpriority()</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_setpriority"><CODE>setpriority()</CODE></A> system
calls. Here's the preamble of the class.</P>
<PRE>
package Nice;
use Carp;
use BSD::Resource;
use strict;
$Nice::DEBUG = 0 unless defined $Nice::DEBUG;</PRE>
This method will be triggered every time an element in the tied array is set
(written). It takes two arguments beyond its self reference: the index at
which we're trying to store something and the value we're trying to put
there. For example:
<PRE>
sub STORE {
my($self, $idx, $value) = @_;
print "[STORE $value at $idx]\n" if _debug;
if ($idx > $self->{BOUND} ) {
confess "Array OOB: $idx > $self->{BOUND}";
}
return $self->{ARRAY}[$idx] = $value;
}</PRE>
<P></P>
<DT><STRONG>DESTROY this</STRONG><BR>
<DD>
This method will be triggered when the tied variable needs to be destructed.
As with the scalar tie class, this is almost never needed in a
language that does its own garbage collection, so this time we'll
just leave it out.
<P></P></DL>
<P>The code we presented at the top of the tied array class accesses many
elements of the array, far more than we've set the bounds to. Therefore,
it will blow up once they try to access beyond the 2nd element of @ary, as
the following output demonstrates:</P>
<PRE>
setting index 0: value of elt 0 now 0
setting index 1: value of elt 1 now 10
setting index 2: value of elt 2 now 20
setting index 3: Array OOB: 3 > 2 at Bounded_Array.pm line 39
Bounded_Array::FETCH called at testba line 12</PRE>
<P>
<H2><A NAME="tying hashes">Tying Hashes</A></H2>
<P>As the first Perl data type to be tied (see dbmopen()), hashes have the
most complete and useful <A HREF="../../lib/Pod/perlfunc.html#item_tie"><CODE>tie()</CODE></A> implementation. A class implementing a
tied hash should define the following methods: TIEHASH is the constructor.
FETCH and STORE access the key and value pairs. EXISTS reports whether a
key is present in the hash, and DELETE deletes one. CLEAR empties the
hash by deleting all the key and value pairs. FIRSTKEY and NEXTKEY
implement the <A HREF="../../lib/Pod/perlfunc.html#item_keys"><CODE>keys()</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_each"><CODE>each()</CODE></A> functions to iterate over all the keys.
And DESTROY is called when the tied variable is garbage collected.</P>
<P>If this seems like a lot, then feel free to inherit from merely the
standard Tie::Hash module for most of your methods, redefining only the
interesting ones. See <A HREF="../../lib/Tie/Hash.html">the Tie::Hash manpage</A> for details.</P>
<P>Remember that Perl distinguishes between a key not existing in the hash,
and the key existing in the hash but having a corresponding value of
<A HREF="../../lib/Pod/perlfunc.html#item_undef"><CODE>undef</CODE></A>. The two possibilities can be tested with the <A HREF="../../lib/Pod/perlfunc.html#item_exists"><CODE>exists()</CODE></A> and
This method will be triggered when the user is going
to iterate through the hash, such as via a <A HREF="../../lib/Pod/perlfunc.html#item_keys"><CODE>keys()</CODE></A> or <A HREF="../../lib/Pod/perlfunc.html#item_each"><CODE>each()</CODE></A>
call.
<PRE>
sub FIRSTKEY {
carp &whowasi if $DEBUG;
my $self = shift;
my $a = keys %{$self->{LIST}}; # reset each() iterator
This method gets triggered during a <A HREF="../../lib/Pod/perlfunc.html#item_keys"><CODE>keys()</CODE></A> or <A HREF="../../lib/Pod/perlfunc.html#item_each"><CODE>each()</CODE></A> iteration. It has a
second argument which is the last key that had been accessed. This is
useful if you're carrying about ordering or calling the iterator from more
than one sequence, or not really storing things in a hash anywhere.
<P>For our example, we're using a real hash so we'll do just the simple
thing, but we'll have to go through the LIST field indirectly.</P>
<PRE>
sub NEXTKEY {
carp &whowasi if $DEBUG;
my $self = shift;
return each %{ $self->{LIST} }
}</PRE>
<P></P>
<DT><STRONG>DESTROY this</STRONG><BR>
<DD>
This method is triggered when a tied hash is about to go out of
scope. You don't really need it unless you're trying to add debugging
or have auxiliary state to clean up. Here's a very simple function:
<PRE>
sub DESTROY {
carp &whowasi if $DEBUG;
}</PRE>
<P></P></DL>
<P>Note that functions such as <A HREF="../../lib/Pod/perlfunc.html#item_keys"><CODE>keys()</CODE></A> and <A HREF="../../lib/Pod/perlfunc.html#item_values"><CODE>values()</CODE></A> may return huge lists
when used on large objects, like DBM files. You may prefer to use the
<A HREF="../../lib/Pod/perlfunc.html#item_each"><CODE>each()</CODE></A> function to iterate over such. Example:</P>
<P>If you intend making use of the object returned from either <A HREF="../../lib/Pod/perlfunc.html#item_tie"><CODE>tie()</CODE></A> or
tied(), and if the tie's target class defines a destructor, there is a
subtle gotcha you <EM>must</EM> guard against.</P>
<P>As setup, consider this (admittedly rather contrived) example of a
tie; all it does is use a file to keep a log of the values assigned to
a scalar.</P>
<PRE>
package Remember;</PRE>
<PRE>
use strict;
use warnings;
use IO::File;</PRE>
<PRE>
sub TIESCALAR {
my $class = shift;
my $filename = shift;
my $handle = new IO::File "> $filename"
or die "Cannot open $filename: $!\n";</PRE>
<PRE>
print $handle "The Start\n";
bless {FH => $handle, Value => 0}, $class;
}</PRE>
<PRE>
sub FETCH {
my $self = shift;
return $self->{Value};
}</PRE>
<PRE>
sub STORE {
my $self = shift;
my $value = shift;
my $handle = $self->{FH};
print $handle "$value\n";
$self->{Value} = $value;
}</PRE>
<PRE>
sub DESTROY {
my $self = shift;
my $handle = $self->{FH};
print $handle "The End\n";
close $handle;
}</PRE>
<PRE>
1;</PRE>
<P>Here is an example that makes use of this tie:</P>
<PRE>
use strict;
use Remember;</PRE>
<PRE>
my $fred;
tie $fred, 'Remember', 'myfile.txt';
$fred = 1;
$fred = 4;
$fred = 5;
untie $fred;
system "cat myfile.txt";</PRE>
<P>This is the output when it is executed:</P>
<PRE>
The Start
1
4
5
The End</PRE>
<P>So far so good. Those of you who have been paying attention will have
spotted that the tied object hasn't been used so far. So lets add an
extra method to the Remember class to allow comments to be included in
the file -- say, something like this:</P>
<PRE>
sub comment {
my $self = shift;
my $text = shift;
my $handle = $self->{FH};
print $handle $text, "\n";
}</PRE>
<P>And here is the previous example modified to use the <CODE>comment</CODE> method
(which requires the tied object):</P>
<PRE>
use strict;
use Remember;</PRE>
<PRE>
my ($fred, $x);
$x = tie $fred, 'Remember', 'myfile.txt';
$fred = 1;
$fred = 4;
comment $x "changing...";
$fred = 5;
untie $fred;
system "cat myfile.txt";</PRE>
<P>When this code is executed there is no output. Here's why:</P>
<P>When a variable is tied, it is associated with the object which is the
return value of the TIESCALAR, TIEARRAY, or TIEHASH function. This
object normally has only one reference, namely, the implicit reference
from the tied variable. When <A HREF="../../lib/Pod/perlfunc.html#item_untie"><CODE>untie()</CODE></A> is called, that reference is
destroyed. Then, as in the first example above, the object's
destructor (DESTROY) is called, which is normal for objects that have
no more valid references; and thus the file is closed.</P>
<P>In the second example, however, we have stored another reference to
the tied object in $x. That means that when <A HREF="../../lib/Pod/perlfunc.html#item_untie"><CODE>untie()</CODE></A> gets called
there will still be a valid reference to the object in existence, so
the destructor is not called at that time, and thus the file is not
closed. The reason there is no output is because the file buffers
have not been flushed to disk.</P>
<P>Now that you know what the problem is, what can you do to avoid it?
Well, the good old <CODE>-w</CODE> flag will spot any instances where you call
<A HREF="../../lib/Pod/perlfunc.html#item_untie"><CODE>untie()</CODE></A> and there are still valid references to the tied object. If
the second script above this near the top <CODE>use warnings 'untie'</CODE>
or was run with the <CODE>-w</CODE> flag, Perl prints this
warning message:</P>
<PRE>
untie attempted while 1 inner references still exist</PRE>
<P>To get the script to work properly and silence the warning make sure
there are no valid references to the tied object <EM>before</EM> <A HREF="../../lib/Pod/perlfunc.html#item_untie"><CODE>untie()</CODE></A> is
called:</P>
<PRE>
undef $x;
untie $fred;</PRE>
<P>
<HR>
<H1><A NAME="see also">SEE ALSO</A></H1>
<P>See <A HREF="../../lib/DB_File.html">the DB_File manpage</A> or <A HREF="../../lib/Config.html">the Config manpage</A> for some interesting <A HREF="../../lib/Pod/perlfunc.html#item_tie"><CODE>tie()</CODE></A> implementations.</P>
<P>
<HR>
<H1><A NAME="bugs">BUGS</A></H1>
<P>Tied arrays are <EM>incomplete</EM>. They are also distinctly lacking something
for the <CODE>$#ARRAY</CODE> access (which is hard, as it's an lvalue), as well as
the other obvious array functions, like push(), pop(), shift(), unshift(),
and splice().</P>
<P>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 <A HREF="../../lib/Pod/perlmodlib.html">the perlmodlib manpage</A> for
source code to MLDBM.</P>
<P>
<HR>
<H1><A NAME="author">AUTHOR</A></H1>
<P>Tom Christiansen</P>
<P>TIEHANDLE by Sven Verdoolaege <<EM><A HREF="mailto:skimo@dns.ufsia.ac.be">skimo@dns.ufsia.ac.be</A></EM>> and Doug MacEachern <<EM><A HREF="mailto:dougm@osf.org">dougm@osf.org</A></EM>></P>