This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Clarify the description of SCALAR in perltie
[perl5.git] / pod / perltie.pod
index 581b4ab..327af04 100644 (file)
@@ -48,7 +48,7 @@ for you--you need to do that explicitly yourself.
 =head2 Tying Scalars
 
 A class implementing a tied scalar should define the following methods:
-TIESCALAR, FETCH, STORE, and possibly DESTROY.
+TIESCALAR, FETCH, STORE, and possibly UNTIE and/or DESTROY.
 
 Let's look at each in turn, using as an example a tie class for
 scalars that allows the user to do something like:
@@ -71,7 +71,7 @@ calls.  Here's the preamble of the class.
     use strict;
     $Nice::DEBUG = 0 unless defined $Nice::DEBUG;
 
-=over
+=over 4
 
 =item TIESCALAR classname, LIST
 
@@ -129,7 +129,9 @@ probably the right thing to do.
 
 This method will be triggered every time the tied variable is set
 (assigned).  Beyond its self reference, it also expects one (and only one)
-argument--the new value the user is trying to assign.
+argument--the new value the user is trying to assign. Don't worry about
+returning a value from STORE -- the semantic of assignment returning the
+assigned value is implemented with FETCH.
 
     sub STORE {
         my $self = shift;
@@ -154,9 +156,14 @@ argument--the new value the user is trying to assign.
         unless (defined setpriority(PRIO_PROCESS, $$self, $new_nicety)) {
             confess "setpriority failed: $!";
         }
-        return $new_nicety;
     }
 
+=item UNTIE this
+
+This method will be triggered when the C<untie> occurs. This can be useful
+if the class needs to know when no further calls will be made. (Except DESTROY
+of course.) See L<The C<untie> Gotcha> below for more details.
+
 =item DESTROY this
 
 This method will be triggered when the tied variable needs to be destructed.
@@ -180,44 +187,37 @@ TIESCALAR classes are certainly possible.
 =head2 Tying Arrays
 
 A class implementing a tied ordinary array should define the following
-methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps DESTROY. 
+methods: TIEARRAY, FETCH, STORE, FETCHSIZE, STORESIZE and perhaps UNTIE and/or DESTROY.
 
 FETCHSIZE and STORESIZE are used to provide C<$#array> and
 equivalent C<scalar(@array)> access.
-    
-The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE are required if the perl
-operator with the corresponding (but lowercase) name is to operate on the
-tied array. The B<Tie::Array> class can be used as a base class to implement
-these in terms of the basic five methods above.  
 
-In addition EXTEND will be called when perl would have pre-extended 
+The methods POP, PUSH, SHIFT, UNSHIFT, SPLICE, DELETE, and EXISTS are
+required if the perl operator with the corresponding (but lowercase) name
+is to operate on the tied array. The B<Tie::Array> class can be used as a
+base class to implement the first five of these in terms of the basic
+methods above.  The default implementations of DELETE and EXISTS in
+B<Tie::Array> simply C<croak>.
+
+In addition EXTEND will be called when perl would have pre-extended
 allocation in a real array.
 
-This means that tied arrays are now I<complete>. The example below needs
-upgrading to illustrate this. (The documentation in B<Tie::Array> is more
-complete.)
+For this discussion, we'll implement an array whose elements are a fixed
+size at creation.  If you try to create an element larger than the fixed
+size, you'll take an exception.  For example:
 
-For this discussion, we'll implement an array whose indices are fixed at
-its creation.  If you try to access anything beyond those bounds, you'll
-take an exception.  For example:
-
-    require Bounded_Array;
-    tie @ary, 'Bounded_Array', 2;
-    $| = 1;
-    for $i (0 .. 10) {
-        print "setting index $i: ";
-        $ary[$i] = 10 * $i;
-        $ary[$i] = 10 * $i;
-        print "value of elt $i now $ary[$i]\n";
-    }
+    use FixedElem_Array;
+    tie @array, 'FixedElem_Array', 3;
+    $array[0] = 'cat';  # ok.
+    $array[1] = 'dogs'; # exception, length('dogs') > 3.
 
 The preamble code for the class is as follows:
 
-    package Bounded_Array;
+    package FixedElem_Array;
     use Carp;
     use strict;
 
-=over
+=over 4
 
 =item TIEARRAY classname, LIST
 
@@ -227,21 +227,22 @@ anonymous ARRAY ref) will be accessed.
 
 In our example, just to show you that you don't I<really> have to return an
 ARRAY reference, we'll choose a HASH reference to represent our object.
-A HASH works out well as a generic record type: the C<{BOUND}> field will
-store the maximum bound allowed, and the C<{ARRAY}> field will hold the
+A HASH works out well as a generic record type: the C<{ELEMSIZE}> field will
+store the maximum element size allowed, and the C<{ARRAY}> field will hold the
 true ARRAY ref.  If someone outside the class tries to dereference the
 object returned (doubtless thinking it an ARRAY ref), they'll blow up.
 This just goes to show you that you should respect an object's privacy.
 
     sub TIEARRAY {
-       my $class = shift;
-       my $bound = shift;
-       confess "usage: tie(\@ary, 'Bounded_Array', max_subscript)"
-           if @_ || $bound =~ /\D/;
-       return bless {
-           BOUND => $bound,
-           ARRAY => [],
-       }, $class;
+      my $class    = shift;
+      my $elemsize = shift;
+      if ( @_ || $elemsize =~ /\D/ ) {
+        croak "usage: tie ARRAY, '" . __PACKAGE__ . "', elem_size";
+      }
+      return bless {
+        ELEMSIZE => $elemsize,
+        ARRAY    => [],
+      }, $class;
     }
 
 =item FETCH this, index
@@ -251,13 +252,17 @@ is accessed (read).  It takes one argument beyond its self reference: the
 index whose value we're trying to fetch.
 
     sub FETCH {
-      my($self,$idx) = @_;
-      if ($idx > $self->{BOUND}) {
-       confess "Array OOB: $idx > $self->{BOUND}";
-      }
-      return $self->{ARRAY}[$idx];
+      my $self  = shift;
+      my $index = shift;
+      return $self->{ARRAY}->[$index];
     }
 
+If a negative array index is used to read from an array, the index
+will be translated to a positive one internally by calling FETCHSIZE
+before being passed to FETCH.  You may disable this feature by
+assigning a true value to the variable C<$NEGATIVE_INDICES> in the
+tied array class.
+
 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
@@ -269,17 +274,189 @@ to keep them at simply one tie type per class.
 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:
+there.
+
+In our example, C<undef> is really C<$self-E<gt>{ELEMSIZE}> number of
+spaces so we have a little more work to do here:
 
     sub STORE {
-      my($self, $idx, $value) = @_;
-      print "[STORE $value at $idx]\n" if _debug;
-      if ($idx > $self->{BOUND} ) {
-        confess "Array OOB: $idx > $self->{BOUND}";
+      my $self = shift;
+      my( $index, $value ) = @_;
+      if ( length $value > $self->{ELEMSIZE} ) {
+        croak "length of $value is greater than $self->{ELEMSIZE}";
+      }
+      # fill in the blanks
+      $self->EXTEND( $index ) if $index > $self->FETCHSIZE();
+      # right justify to keep element size for smaller elements
+      $self->{ARRAY}->[$index] = sprintf "%$self->{ELEMSIZE}s", $value;
+    }
+
+Negative indexes are treated the same as with FETCH.
+
+=item FETCHSIZE this
+
+Returns the total number of items in the tied array associated with
+object I<this>. (Equivalent to C<scalar(@array)>).  For example:
+
+    sub FETCHSIZE {
+      my $self = shift;
+      return scalar @{$self->{ARRAY}};
+    }
+
+=item STORESIZE this, count
+
+Sets the total number of items in the tied array associated with
+object I<this> to be I<count>. If this makes the array larger then
+class's mapping of C<undef> should be returned for new positions.
+If the array becomes smaller then entries beyond count should be
+deleted. 
+
+In our example, 'undef' is really an element containing
+C<$self-E<gt>{ELEMSIZE}> number of spaces.  Observe:
+
+    sub STORESIZE {
+      my $self  = shift;
+      my $count = shift;
+      if ( $count > $self->FETCHSIZE() ) {
+        foreach ( $count - $self->FETCHSIZE() .. $count ) {
+          $self->STORE( $_, '' );
+        }
+      } elsif ( $count < $self->FETCHSIZE() ) {
+        foreach ( 0 .. $self->FETCHSIZE() - $count - 2 ) {
+          $self->POP();
+        }
+      }
+    }
+
+=item EXTEND this, count
+
+Informative call that array is likely to grow to have I<count> entries.
+Can be used to optimize allocation. This method need do nothing.
+
+In our example, we want to make sure there are no blank (C<undef>)
+entries, so C<EXTEND> will make use of C<STORESIZE> to fill elements
+as needed:
+
+    sub EXTEND {   
+      my $self  = shift;
+      my $count = shift;
+      $self->STORESIZE( $count );
+    }
+
+=item EXISTS this, key
+
+Verify that the element at index I<key> exists in the tied array I<this>.
+
+In our example, we will determine that if an element consists of
+C<$self-E<gt>{ELEMSIZE}> spaces only, it does not exist:
+
+    sub EXISTS {
+      my $self  = shift;
+      my $index = shift;
+      return 0 if ! defined $self->{ARRAY}->[$index] ||
+                  $self->{ARRAY}->[$index] eq ' ' x $self->{ELEMSIZE};
+      return 1;
+    }
+
+=item DELETE this, key
+
+Delete the element at index I<key> from the tied array I<this>.
+
+In our example, a deleted item is C<$self-E<gt>{ELEMSIZE}> spaces:
+
+    sub DELETE {
+      my $self  = shift;
+      my $index = shift;
+      return $self->STORE( $index, '' );
+    }
+
+=item CLEAR this
+
+Clear (remove, delete, ...) all values from the tied array associated with
+object I<this>.  For example:
+
+    sub CLEAR {
+      my $self = shift;
+      return $self->{ARRAY} = [];
+    }
+
+=item PUSH this, LIST 
+
+Append elements of I<LIST> to the array.  For example:
+
+    sub PUSH {  
+      my $self = shift;
+      my @list = @_;
+      my $last = $self->FETCHSIZE();
+      $self->STORE( $last + $_, $list[$_] ) foreach 0 .. $#list;
+      return $self->FETCHSIZE();
+    }   
+
+=item POP this
+
+Remove last element of the array and return it.  For example:
+
+    sub POP {
+      my $self = shift;
+      return pop @{$self->{ARRAY}};
+    }
+
+=item SHIFT this
+
+Remove the first element of the array (shifting other elements down)
+and return it.  For example:
+
+    sub SHIFT {
+      my $self = shift;
+      return shift @{$self->{ARRAY}};
+    }
+
+=item UNSHIFT this, LIST 
+
+Insert LIST elements at the beginning of the array, moving existing elements
+up to make room.  For example:
+
+    sub UNSHIFT {
+      my $self = shift;
+      my @list = @_;
+      my $size = scalar( @list );
+      # make room for our list
+      @{$self->{ARRAY}}[ $size .. $#{$self->{ARRAY}} + $size ]
+       = @{$self->{ARRAY}};
+      $self->STORE( $_, $list[$_] ) foreach 0 .. $#list;
+    }
+
+=item SPLICE this, offset, length, LIST
+
+Perform the equivalent of C<splice> on the array. 
+
+I<offset> is optional and defaults to zero, negative values count back 
+from the end of the array. 
+
+I<length> is optional and defaults to rest of the array.
+
+I<LIST> may be empty.
+
+Returns a list of the original I<length> elements at I<offset>.
+
+In our example, we'll use a little shortcut if there is a I<LIST>:
+
+    sub SPLICE {
+      my $self   = shift;
+      my $offset = shift || 0;
+      my $length = shift || $self->FETCHSIZE() - $offset;
+      my @list   = (); 
+      if ( @_ ) {
+        tie @list, __PACKAGE__, $self->{ELEMSIZE};
+        @list   = @_;
       }
-      return $self->{ARRAY}[$idx] = $value;
+      return splice @{$self->{ARRAY}}, $offset, $length, @list;
     }
 
+=item UNTIE this
+
+Will be called when C<untie> happens. (See L<The C<untie> Gotcha> below.)
+
 =item DESTROY this
 
 This method will be triggered when the tied variable needs to be destructed.
@@ -289,30 +466,20 @@ just leave it out.
 
 =back
 
-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:
-
-    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
-
 =head2 Tying Hashes
 
-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.
+Hashes were the first Perl data type to be tied (see dbmopen()).  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. SCALAR is triggered when the tied hash is evaluated in scalar 
+context. UNTIE is called when C<untie> happens, and DESTROY is called when
+the tied variable is garbage collected.
 
 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
+standard Tie::StdHash 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,
@@ -382,7 +549,7 @@ that calls it.
 
 Here are the methods for the DotFiles tied hash.
 
-=over
+=over 4
 
 =item TIEHASH classname, LIST
 
@@ -591,6 +758,29 @@ thing, but we'll have to go through the LIST field indirectly.
        return each %{ $self->{LIST} }
     }
 
+=item SCALAR this
+
+This is called when the hash is evaluated in scalar context. In order
+to mimic the behaviour of untied hashes, this method should return a
+false value when the tied hash is considered empty. If this method does
+not exist, perl will make some educated guesses and return true when
+the hash is inside an iteration. If this isn't the case, FIRSTKEY is
+called, and the result will be a false value if FIRSTKEY returns the empty
+list, true otherwise.
+
+In our example we can just call C<scalar> on the underlying hash
+referenced by C<$self-E<gt>{LIST}>:
+
+    sub SCALAR {
+       carp &whowasi if $DEBUG;
+       my $self = shift;
+       return scalar %{ $self->{LIST} }
+    }
+
+=item UNTIE this
+
+This is called when C<untie> occurs.  See L<The C<untie> Gotcha> below.
+
 =item DESTROY this
 
 This method is triggered when a tied hash is about to go out of
@@ -621,19 +811,26 @@ This is partially implemented now.
 
 A class implementing a tied filehandle should define the following
 methods: TIEHANDLE, at least one of PRINT, PRINTF, WRITE, READLINE, GETC,
-READ, and possibly CLOSE and DESTROY.  The class can also provide: BINMODE, 
+READ, and possibly CLOSE, UNTIE and DESTROY.  The class can also provide: BINMODE,
 OPEN, EOF, FILENO, SEEK, TELL - if the corresponding perl operators are
 used on the handle.
 
-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.
+When STDERR is tied, its PRINT method will be called to issue warnings
+and error messages.  This feature is temporarily disabled during the call, 
+which means you can use C<warn()> inside PRINT without starting a recursive
+loop.  And just like C<__WARN__> and C<__DIE__> handlers, STDERR's PRINT
+method may be called to report parser errors, so the caveats mentioned under 
+L<perlvar/%SIG> apply.
+
+All of this 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
+=over 4
 
 =item TIEHANDLE classname, LIST
 
@@ -683,7 +880,7 @@ or C<sysread> functions.
 
     sub READ {
        my $self = shift;
-       my $$bufref = \$_[0];
+       my $bufref = \$_[0];
        my(undef,$len,$offset) = @_;
        print "READ called, \$buf=$bufref, \$len=$len, \$offset=$offset";
        # add to $$bufref, set $len to number of characters read
@@ -710,6 +907,12 @@ function.
 
     sub CLOSE { print "CLOSE called.\n" }
 
+=item UNTIE this
+
+As with the other types of ties, this method will be called when C<untie> happens.
+It may be appropriate to "auto CLOSE" when this occurs.  See
+L<The C<untie> Gotcha> below.
+
 =item DESTROY this
 
 As with the other types of ties, this method will be called when the
@@ -728,6 +931,11 @@ Here's how to use our little example:
     print FOO $a, " plus ", $b, " equals ", $a + $b, "\n";
     print <FOO>;
 
+=head2 UNTIE this
+
+You can define for all tie types an UNTIE method that will be called
+at untie().  See L<The C<untie> Gotcha> below.
+
 =head2 The C<untie> Gotcha
 
 If you intend making use of the object returned from either tie() or
@@ -741,6 +949,7 @@ a scalar.
     package Remember;
 
     use strict;
+    use warnings;
     use IO::File;
 
     sub TIESCALAR {
@@ -834,16 +1043,18 @@ 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
+the tied object in $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
+Prior to the introduction of the optional UNTIE method the only way
+was the good old C<-w> flag. Which 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
+the second script above this near the top C<use warnings 'untie'>
+or was run with the C<-w> flag, Perl prints this
 warning message:
 
     untie attempted while 1 inner references still exist
@@ -855,16 +1066,47 @@ called:
     undef $x;
     untie $fred;
 
+Now that UNTIE exists the class designer can decide which parts of the
+class functionality are really associated with C<untie> and which with
+the object being destroyed. What makes sense for a given class depends
+on whether the inner references are being kept so that non-tie-related
+methods can be called on the object. But in most cases it probably makes
+sense to move the functionality that would have been in DESTROY to the UNTIE
+method.
+
+If the UNTIE method exists then the warning above does not occur. Instead the
+UNTIE method is passed the count of "extra" references and can issue its own
+warning if appropriate. e.g. to replicate the no UNTIE case this method can
+be used:
+
+    sub UNTIE
+    {
+     my ($obj,$count) = @_;
+     carp "untie attempted while $count inner references still exist" if $count;
+    }
+
 =head1 SEE ALSO
 
 See L<DB_File> or L<Config> for some interesting tie() implementations.
+A good starting point for many tie() implementations is with one of the
+modules L<Tie::Scalar>, L<Tie::Array>, L<Tie::Hash>, or L<Tie::Handle>.
 
 =head1 BUGS
 
-Tied arrays are I<incomplete>.  They are also distinctly lacking something
-for the C<$#ARRAY> access (which is hard, as it's an lvalue), as well as
-the other obvious array functions, like push(), pop(), shift(), unshift(),
-and splice().
+The bucket usage information provided by C<scalar(%hash)> is not
+available.  What this means is that using %tied_hash in boolean
+context doesn't work right (currently this always tests false,
+regardless of whether the hash is empty or hash elements).
+
+Localizing tied arrays or hashes does not work.  After exiting the
+scope the arrays or the hashes are not restored.
+
+Counting the number of entries in a hash via C<scalar(keys(%hash))>
+or C<scalar(values(%hash)>) is inefficient since it needs to iterate
+through all the entries with FIRSTKEY/NEXTKEY.
+
+Tied hash/array slices cause multiple FETCH/STORE pairs, there are no
+tie methods for slice operations.
 
 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
@@ -874,8 +1116,17 @@ module that does attempt to address this need partially is the MLDBM
 module.  Check your nearest CPAN site as described in L<perlmodlib> for
 source code to MLDBM.
 
+Tied filehandles are still incomplete.  sysopen(), truncate(),
+flock(), fcntl(), stat() and -X can't currently be trapped.
+
 =head1 AUTHOR
 
 Tom Christiansen
 
 TIEHANDLE by Sven Verdoolaege <F<skimo@dns.ufsia.ac.be>> and Doug MacEachern <F<dougm@osf.org>>
+
+UNTIE by Nick Ing-Simmons <F<nick@ing-simmons.net>>
+
+SCALAR by Tassilo von Parseval <F<tassilo.von.parseval@rwth-aachen.de>>
+
+Tying Arrays by Casey West <F<casey@geeknest.com>>