This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[inseparable changes from match from perl-5.003_97 to perl-5.003_97a]
[perl5.git] / pod / perltie.pod
index 658425e..847340d 100644 (file)
@@ -13,8 +13,8 @@ perltie - how to hide an object class in a simple variable
 =head1 DESCRIPTION
 
 Prior to release 5.0 of Perl, a programmer could use dbmopen()
-to magically connect an on-disk database in the standard Unix dbm(3x)
-format to a %HASH in their program.  However, their Perl was either
+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.
 
@@ -33,13 +33,14 @@ In the tie() call, C<VARIABLE> is the name of the variable to be
 enchanted.  C<CLASSNAME> is the name of a class implementing objects of
 the correct type.  Any additional arguments in the C<LIST> are passed to
 the appropriate constructor method for that class--meaning TIESCALAR(),
-TIEARRAY(), or TIEHASH().  (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 C<CLASSNAME>. (You don't actually
-have to return a reference to a right "type" (e.g. HASH or C<CLASSNAME>)
-so long as it's a properly blessed object.)  You can also retrieve
-a reference to the underlying object using the tied() function.
+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
+C<CLASSNAME>. (You don't actually have to return a reference to a right
+"type" (e.g., HASH or C<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 C<use> or C<require> a module
 for you--you need to do that explicitly yourself.
@@ -59,10 +60,10 @@ 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!
 
-We'll use Jarkko Hietaniemi F<E<lt>Jarkko.Hietaniemi@hut.fiE<gt>>'s
-BSD::Resource class (not included) to access the PRIO_PROCESS, PRIO_MIN,
-and PRIO_MAX constants from your system, as well as the getpriority() and
-setpriority() system calls.  Here's the preamble of the class.
+We'll use Jarkko Hietaniemi <F<jhi@iki.fi>>'s BSD::Resource class (not
+included) to access the PRIO_PROCESS, PRIO_MIN, and PRIO_MAX constants
+from your system, as well as the getpriority() and setpriority() system
+calls.  Here's the preamble of the class.
 
     package Nice;
     use Carp;
@@ -104,8 +105,8 @@ variable C<$^W> to see whether to emit a bit of noise anyway.
 
 This method will be triggered every time the tied variable is accessed
 (read).  It takes no arguments beyond its self reference, which is the
-object representing the scalar we're dealing with.  Since in this case
-we're just using a SCALAR ref for the tied scalar object, a simple $$self
+object representing the scalar we're dealing with.  Because in this case
+we're using just a SCALAR ref for the tied scalar object, a simple $$self
 allows the method to get at the real value stored there.  In our example
 below, that real value is the process ID to which we've tied our variable.
 
@@ -159,7 +160,7 @@ argument--the new value the user is trying to assign.
 =item DESTROY this
 
 This method will be triggered when the tied variable needs to be destructed.
-As with other object classes, such a method is seldom ncessary, since Perl
+As with other object classes, such a method is seldom necessary, because Perl
 deallocates its moribund object's memory for you automatically--this isn't
 C++, you know.  We'll use a DESTROY method here for debugging purposes only.
 
@@ -172,7 +173,7 @@ C++, you know.  We'll use a DESTROY method here for debugging purposes only.
 =back
 
 That's about all there is to it.  Actually, it's more than all there
-is to it, since we've done a few nice things here for the sake
+is to it, because we've done a few nice things here for the sake
 of completeness, robustness, and general aesthetics.  Simpler
 TIESCALAR classes are certainly possible.
 
@@ -252,7 +253,7 @@ As you may have noticed, the name of the FETCH method (et al.) is the same
 for all accesses, even though the constructors differ in names (TIESCALAR
 vs TIEARRAY).  While in theory you could have the same class servicing
 several tied types, in practice this becomes cumbersome, and it's easiest
-to simply keep them at one tie type per class.
+to keep them at simply one tie type per class.
 
 =item STORE this, index, value
 
@@ -273,7 +274,7 @@ there.  For example:
 =item DESTROY this
 
 This method will be triggered when the tied variable needs to be destructed.
-As with the sclar tie class, this is almost never needed in a
+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.
 
@@ -292,19 +293,18 @@ the following output demonstrates:
 
 =head2 Tying Hashes
 
-As the first Perl data type to be tied (see dbmopen()), associative arrays
-have the most complete and useful tie() implementation.  A class
-implementing a tied associative array 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 keys() and each()
-functions to iterate over all the keys.  And DESTROY is called when the
-tied variable is garbage collected.
+As the first Perl data type to be tied (see dbmopen()), hashes have the
+most complete and useful tie() 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 keys() and each() functions to iterate over all the keys.
+And DESTROY is called when the tied variable is garbage collected.
 
-If this seems like a lot, then feel free to merely inherit
-from the standard Tie::Hash module for most of your methods, redefining only
-the interesting ones.  See L<Tie::Hash> for details.
+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 L<Tie::Hash> for details.
 
 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
@@ -312,8 +312,8 @@ C<undef>.  The two possibilities can be tested with the C<exists()> and
 C<defined()> functions.
 
 Here's an example of a somewhat interesting tied hash class:  it gives you
-a hash representing a particular user's dotfiles.  You index into the hash
-with the name of the file (minus the dot) and you get back that dotfile's
+a hash representing a particular user's dot files.  You index into the hash
+with the name of the file (minus the dot) and you get back that dot file's
 contents.  For example:
 
     use DotFiles;
@@ -322,7 +322,7 @@ contents.  For example:
          $dot{login}   =~ /MANPATH/ ||
          $dot{cshrc}   =~ /MANPATH/    )
     {
-       print "you seem to set your manpath\n";
+       print "you seem to set your MANPATH\n";
     }
 
 Or here's another sample of using our tied class:
@@ -346,7 +346,7 @@ whose dot files this object represents
 
 =item HOME
 
-where those dotfiles live
+where those dot files live
 
 =item CLOBBER
 
@@ -354,7 +354,7 @@ whether we should try to change or remove those dot files
 
 =item LIST
 
-the hash of dotfile names and content mappings
+the hash of dot file names and content mappings
 
 =back
 
@@ -366,7 +366,7 @@ Here's the start of F<Dotfiles.pm>:
     my $DEBUG = 0;
     sub debug { $DEBUG = @_ ? shift : 1 }
 
-For our example, we want to able to emit debugging info to help in tracing
+For our example, we want to be able to emit debugging info to help in tracing
 during development.  We keep also one convenience function around
 internally to help print out warnings; whowasi() returns the function name
 that calls it.
@@ -412,8 +412,8 @@ Here's the constructor:
 
 It's probably worth mentioning that if you're going to filetest the
 return values out of a readdir, you'd better prepend the directory
-in question.  Otherwise, since we didn't chdir() there, it would
-have been testing the wrong file.  
+in question.  Otherwise, because we didn't chdir() there, it would
+have been testing the wrong file.
 
 =item FETCH this, key
 
@@ -444,7 +444,7 @@ Here's the fetch for our DotFiles example.
 
 It was easy to write by having it call the Unix cat(1) command, but it
 would probably be more portable to open the file manually (and somewhat
-more efficient).  Of course, since dot files are a Unixy concept, we're
+more efficient).  Of course, because dot files are a Unixy concept, we're
 not that concerned.
 
 =item STORE this, key, value
@@ -525,14 +525,14 @@ the caller whether the file was successfully deleted.
 This method is triggered when the whole hash is to be cleared, usually by
 assigning the empty list to it.
 
-In our example, that would remove all the user's dotfiles!  It's such a
+In our example, that would remove all the user's dot files!  It's such a
 dangerous thing that they'll have to set CLOBBER to something higher than
 1 to make it happen.
 
     sub CLEAR    {
        carp &whowasi if $DEBUG;
        my $self = shift;
-       croak "@{[&whowasi]}: won't remove all dotfiles for $self->{USER}"
+       croak "@{[&whowasi]}: won't remove all dot files for $self->{USER}"
            unless $self->{CLOBBER} > 1;
        my $dot;
        foreach $dot ( keys %{$self->{LIST}}) {
@@ -573,8 +573,8 @@ 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.
 
-For our example, we our using a real hash so we'll just do the simple
-thing, but we'll have to indirect through the LIST field.
+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.
 
     sub NEXTKEY  {
        carp &whowasi if $DEBUG;
@@ -608,7 +608,206 @@ use the each() function to iterate over such.  Example:
 
 =head2 Tying FileHandles
 
-This isn't implemented yet.  Sorry; maybe someday.
+This is partially implemented now.
+
+A class implementing a tied filehandle should define the following
+methods: TIEHANDLE, at least one of PRINT, READLINE, GETC, or READ,
+and possibly DESTROY.
+
+It is especially useful when perl is embedded in some other program,
+where output to STDOUT and STDERR may have to be redirected in some
+special way. See nvi and the Apache module for examples.
+
+In our example we're going to create a shouting handle.
+
+    package Shout;
+
+=over
+
+=item TIEHANDLE classname, LIST
+
+This is the constructor for the class.  That means it is expected to
+return a blessed reference of some sort. The reference can be used to
+hold some internal information.
+
+    sub TIEHANDLE { print "<shout>\n"; my $i; bless \$i, shift }
+
+=item PRINT this, LIST
+
+This method will be triggered every time the tied handle is printed to.
+Beyond its self reference it also expects the list that was passed to
+the print function.
+
+    sub PRINT { $r = shift; $$r++; print join($,,map(uc($_),@_)),$\ }
+
+=item READ this LIST
+
+This method will be called when the handle is read from via the C<read>
+or C<sysread> functions.
+
+    sub READ {
+       $r = shift;
+       my($buf,$len,$offset) = @_;
+       print "READ called, \$buf=$buf, \$len=$len, \$offset=$offset";
+    }
+
+=item READLINE this
+
+This method will be called when the handle is read from via <HANDLE>.
+The method should return undef when there is no more data.
+
+    sub READLINE { $r = shift; "PRINT called $$r times\n"; }
+
+=item GETC this
+
+This method will be called when the C<getc> function is called.
+
+    sub GETC { print "Don't GETC, Get Perl"; return "a"; }
+
+=item DESTROY this
+
+As with the other types of ties, this method will be called when the
+tied handle is about to be destroyed. This is useful for debugging and
+possibly cleaning up.
+
+    sub DESTROY { print "</shout>\n" }
+
+=back
+
+Here's how to use our little example:
+
+    tie(*FOO,'Shout');
+    print FOO "hello\n";
+    $a = 4; $b = 6;
+    print FOO $a, " plus ", $b, " equals ", $a + $b, "\n";
+    print <FOO>;
+
+=head2 The C<untie> Gotcha
+
+If you intend making use of the object returned from either tie() or
+tied(), and if the tie's target class defines a destructor, there is a
+subtle gotcha you I<must> guard against.
+
+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.
+
+    package Remember;
+
+    use strict;
+    use IO::File;
+
+    sub TIESCALAR {
+        my $class = shift;
+        my $filename = shift;
+        my $handle = new IO::File "> $filename"
+                         or die "Cannot open $filename: $!\n";
+
+        print $handle "The Start\n";
+        bless {FH => $handle, Value => 0}, $class;
+    }
+
+    sub FETCH {
+        my $self = shift;
+        return $self->{Value};
+    }
+
+    sub STORE {
+        my $self = shift;
+        my $value = shift;
+        my $handle = $self->{FH};
+        print $handle "$value\n";
+        $self->{Value} = $value;
+    }
+
+    sub DESTROY {
+        my $self = shift;
+        my $handle = $self->{FH};
+        print $handle "The End\n";
+        close $handle;
+    }
+
+    1;
+
+Here is an example that makes use of this tie:
+
+    use strict;
+    use Remember;
+
+    my $fred;
+    tie $fred, 'Remember', 'myfile.txt';
+    $fred = 1;
+    $fred = 4;
+    $fred = 5;
+    untie $fred;
+    system "cat myfile.txt";
+
+This is the output when it is executed:
+
+    The Start
+    1
+    4
+    5
+    The End
+
+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:
+
+    sub comment {
+        my $self = shift;
+        my $text = shift;
+        my $handle = $self->{FH};
+        print $handle $text, "\n";
+    }
+
+And here is the previous example modified to use the C<comment> method
+(which requires the tied object):
+
+    use strict;
+    use Remember;
+
+    my ($fred, $x);
+    $x = tie $fred, 'Remember', 'myfile.txt';
+    $fred = 1;
+    $fred = 4;
+    comment $x "changing...";
+    $fred = 5;
+    untie $fred;
+    system "cat myfile.txt";
+
+When this code is executed there is no output.  Here's why:
+
+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 untie() 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.
+
+In the second example, however, we have stored another reference to
+the tied object in C<$x>.  That means that when untie() 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.
+
+Now that you know what the problem is, what can you do to avoid it?
+Well, the good old C<-w> flag will spot any instances where you call
+untie() and there are still valid references to the tied object.  If
+the second script above is run with the C<-w> flag, Perl prints this
+warning message:
+
+    untie attempted while 1 inner references still exist
+
+To get the script to work properly and silence the warning make sure
+there are no valid references to the tied object I<before> untie() is
+called:
+
+    undef $x;
+    untie $fred;
 
 =head1 SEE ALSO
 
@@ -625,10 +824,12 @@ 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 partially address this need is the MLDBM
+module that does attempt to address this need partially is the MLDBM
 module.  Check your nearest CPAN site as described in L<perlmod> for
 source code to MLDBM.
 
 =head1 AUTHOR
 
 Tom Christiansen
+
+TIEHANDLE by Sven Verdoolaege <F<skimo@dns.ufsia.ac.be>>