This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Re: [ID 20000525.003] perldoc fails when Makefile.PL is in cwd
[perl5.git] / lib / overload.pm
index 43fef8a..f7772c1 100644 (file)
@@ -1,5 +1,7 @@
 package overload;
 
+$overload::hint_bits = 0x20000;
+
 sub nil {}
 
 sub OVERLOAD {
@@ -87,7 +89,7 @@ sub AddrRef {
 }
 
 sub StrVal {
-  (OverloadedStringify($_[0])) ?
+  (OverloadedStringify($_[0]) or ref($_[0]) eq 'Regexp') ?
     (AddrRef(shift)) :
     "$_[0]";
 }
@@ -113,21 +115,23 @@ sub mycan {                               # Real can would leave stubs.
 
 %ops = ( with_assign     => "+ - * / % ** << >> x .",
         assign           => "+= -= *= /= %= **= <<= >>= x= .=",
-        str_comparison   => "< <= >  >= == !=",
+        num_comparison   => "< <= >  >= == !=",
         '3way_comparison'=> "<=> cmp",
-        num_comparison   => "lt le gt ge eq ne",
+        str_comparison   => "lt le gt ge eq ne",
         binary           => "& | ^",
         unary            => "neg ! ~",
         mutators         => '++ --',
         func             => "atan2 cos sin exp abs log sqrt",
         conversion       => 'bool "" 0+',
+        iterators        => '<>',
+        dereferencing    => '${} @{} %{} &{} *{}',
         special          => 'nomethod fallback =');
 
 sub constant {
   # Arguments: what, sub
   while (@_) {
     $^H{$_[0]} = $_[1];
-    $^H |= $constants{$_[0]} | 0x20000;
+    $^H |= $constants{$_[0]} | $overload::hint_bits;
     shift, shift;
   }
 }
@@ -167,13 +171,6 @@ overload - Package for overloading perl operations
     ...
     $strval = overload::StrVal $b;
 
-=head1 CAVEAT SCRIPTOR
-
-Overloading of operators is a subject not to be taken lightly.
-Neither its precise implementation, syntax, nor semantics are
-100% endorsed by Larry Wall.  So any of these may be changed 
-at some point in the future.
-
 =head1 DESCRIPTION
 
 =head2 Declaration of overloaded functions
@@ -274,7 +271,7 @@ value of their arguments, and may leave it as is.  The result is going
 to be assigned to the value in the left-hand-side if different from
 this value.
 
-This allows for the same method to be used as averloaded C<+=> and
+This allows for the same method to be used as overloaded C<+=> and
 C<+>.  Note that this is I<allowed>, but not recommended, since by the
 semantic of L<"Fallback"> Perl will call the method for C<+> anyway,
 if C<+=> is not overloaded.
@@ -283,7 +280,7 @@ if C<+=> is not overloaded.
 
 B<Warning.>  Due to the presense of assignment versions of operations,
 routines which may be called in assignment context may create 
-self-referencial structures.  Currently Perl will not free self-referential 
+self-referential structures.  Currently Perl will not free self-referential 
 structures until cycles are C<explicitly> broken.  You may get problems
 when traversing your structures too.
 
@@ -362,12 +359,29 @@ for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
 
     "bool", "\"\"", "0+",
 
-If one or two of these operations are unavailable, the remaining ones can
+If one or two of these operations are not overloaded, the remaining ones can
 be used instead.  C<bool> is used in the flow control operators
 (like C<while>) and for the ternary "C<?:>" operation.  These functions can
 return any arbitrary Perl value.  If the corresponding operation for this value
 is overloaded too, that operation will be called again with this value.
 
+=item * I<Iteration>
+
+    "<>"
+
+If not overloaded, the argument will be converted to a filehandle or
+glob (which may require a stringification).  The same overloading
+happens both for the I<read-filehandle> syntax C<E<lt>$varE<gt>> and
+I<globbing> syntax C<E<lt>${var}E<gt>>.
+
+=item * I<Dereferencing>
+
+    '${}', '@{}', '%{}', '&{}', '*{}'.
+
+If not overloaded, the argument will be dereferenced I<as is>, thus
+should be of correct type.  These functions should return a reference
+of correct type, or another object with overloaded dereferencing.
+
 =item * I<Special>
 
     "nomethod", "fallback", "=",
@@ -384,14 +398,16 @@ A computer-readable form of the above table is available in the hash
 
  with_assign     => '+ - * / % ** << >> x .',
  assign                  => '+= -= *= /= %= **= <<= >>= x= .=',
str_comparison          => '< <= > >= == !=',
num_comparison          => '< <= > >= == !=',
  '3way_comparison'=> '<=> cmp',
num_comparison          => 'lt le gt ge eq ne',
str_comparison          => 'lt le gt ge eq ne',
  binary                  => '& | ^',
  unary           => 'neg ! ~',
  mutators        => '++ --',
  func            => 'atan2 cos sin exp abs log sqrt',
  conversion      => 'bool "" 0+',
+ iterators       => '<>',
+ dereferencing   => '${} @{} %{} &{} *{}',
  special         => 'nomethod fallback ='
 
 =head2 Inheritance and overloading
@@ -537,7 +553,7 @@ C<'='> was overloaded with C<\&clone>.
 
 =back
 
-Same behaviour is triggered by C<$b = $a++>, which is consider a synonim for
+Same behaviour is triggered by C<$b = $a++>, which is consider a synonym for
 C<$b = $a; ++$a>.
 
 =head1 MAGIC AUTOGENERATION
@@ -589,6 +605,14 @@ C<E<lt>=E<gt>> or C<cmp>:
     <, >, <=, >=, ==, !=       in terms of <=>
     lt, gt, le, ge, eq, ne     in terms of cmp
 
+=item I<Iterator>
+
+    <>                         in terms of builtin operations
+
+=item I<Dereferencing>
+
+    ${} @{} %{} &{} *{}                in terms of builtin operations
+
 =item I<Copy operator>
 
 can be expressed in terms of an assignment to the dereferenced value, if this
@@ -748,7 +772,7 @@ There is no size penalty for data if overload is not used. The only
 size penalty if overload is used in some package is that I<all> the
 packages acquire a magic during the next C<bless>ing into the
 package. This magic is three-words-long for packages without
-overloading, and carries the cache tabel if the package is overloaded.
+overloading, and carries the cache table if the package is overloaded.
 
 Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is 
 carried out before any operation that can imply an assignment to the
@@ -760,8 +784,8 @@ to be changed are constant (but this is not enforced).
 
 =head1 Metaphor clash
 
-One may wonder why the semantic of overloaded C<=> is so counterintuive.
-If it I<looks> counterintuive to you, you are subject to a metaphor 
+One may wonder why the semantic of overloaded C<=> is so counter intuitive.
+If it I<looks> counter intuitive to you, you are subject to a metaphor 
 clash.  
 
 Here is a Perl object metaphor:
@@ -851,6 +875,133 @@ numeric value.)  This prints:
   seven=vii, seven=7, eight=8
   seven contains `i'
 
+=head2 Two-face references
+
+Suppose you want to create an object which is accessible as both an
+array reference and a hash reference, similar to the
+L<pseudo-hash|perlref/"Pseudo-hashes: Using an array as a hash">
+builtin Perl type.  Let's make it better than a pseudo-hash by
+allowing index 0 to be treated as a normal element.
+
+  package two_refs;
+  use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
+  sub new { 
+    my $p = shift; 
+    bless \ [@_], $p;
+  }
+  sub gethash {
+    my %h;
+    my $self = shift;
+    tie %h, ref $self, $self;
+    \%h;
+  }
+
+  sub TIEHASH { my $p = shift; bless \ shift, $p }
+  my %fields;
+  my $i = 0;
+  $fields{$_} = $i++ foreach qw{zero one two three};
+  sub STORE { 
+    my $self = ${shift()};
+    my $key = $fields{shift()};
+    defined $key or die "Out of band access";
+    $$self->[$key] = shift;
+  }
+  sub FETCH { 
+    my $self = ${shift()};
+    my $key = $fields{shift()};
+    defined $key or die "Out of band access";
+    $$self->[$key];
+  }
+
+Now one can access an object using both the array and hash syntax:
+
+  my $bar = new two_refs 3,4,5,6;
+  $bar->[2] = 11;
+  $bar->{two} == 11 or die 'bad hash fetch';
+
+Note several important features of this example.  First of all, the
+I<actual> type of $bar is a scalar reference, and we do not overload
+the scalar dereference.  Thus we can get the I<actual> non-overloaded
+contents of $bar by just using C<$$bar> (what we do in functions which
+overload dereference).  Similarly, the object returned by the
+TIEHASH() method is a scalar reference.
+
+Second, we create a new tied hash each time the hash syntax is used.
+This allows us not to worry about a possibility of a reference loop,
+would would lead to a memory leak.
+
+Both these problems can be cured.  Say, if we want to overload hash
+dereference on a reference to an object which is I<implemented> as a
+hash itself, the only problem one has to circumvent is how to access
+this I<actual> hash (as opposed to the I<virtual> exhibited by
+overloaded dereference operator).  Here is one possible fetching routine:
+
+  sub access_hash {
+    my ($self, $key) = (shift, shift);
+    my $class = ref $self;
+    bless $self, 'overload::dummy'; # Disable overloading of %{} 
+    my $out = $self->{$key};
+    bless $self, $class;       # Restore overloading
+    $out;
+  }
+
+To move creation of the tied hash on each access, one may an extra
+level of indirection which allows a non-circular structure of references:
+
+  package two_refs1;
+  use overload '%{}' => sub { ${shift()}->[1] },
+               '@{}' => sub { ${shift()}->[0] };
+  sub new { 
+    my $p = shift; 
+    my $a = [@_];
+    my %h;
+    tie %h, $p, $a;
+    bless \ [$a, \%h], $p;
+  }
+  sub gethash {
+    my %h;
+    my $self = shift;
+    tie %h, ref $self, $self;
+    \%h;
+  }
+
+  sub TIEHASH { my $p = shift; bless \ shift, $p }
+  my %fields;
+  my $i = 0;
+  $fields{$_} = $i++ foreach qw{zero one two three};
+  sub STORE { 
+    my $a = ${shift()};
+    my $key = $fields{shift()};
+    defined $key or die "Out of band access";
+    $a->[$key] = shift;
+  }
+  sub FETCH { 
+    my $a = ${shift()};
+    my $key = $fields{shift()};
+    defined $key or die "Out of band access";
+    $a->[$key];
+  }
+
+Now if $baz is overloaded like this, then C<$bar> is a reference to a
+reference to the intermediate array, which keeps a reference to an
+actual array, and the access hash.  The tie()ing object for the access
+hash is also a reference to a reference to the actual array, so 
+
+=over
+
+=item *
+
+There are no loops of references.
+
+=item *
+
+Both "objects" which are blessed into the class C<two_refs1> are
+references to a reference to an array, thus references to a I<scalar>.
+Thus the accessor expression C<$$foo-E<gt>[$ind]> involves no
+overloaded operations.
+
+=back
+
 =head2 Symbolic calculator
 
 Put this in F<symbolic.pm> in your Perl library directory:
@@ -868,7 +1019,7 @@ Put this in F<symbolic.pm> in your Perl library directory:
 This module is very unusual as overloaded modules go: it does not
 provide any usual overloaded operators, instead it provides the L<Last
 Resort> operator C<nomethod>.  In this example the corresponding
-subroutine returns an object which encupsulates operations done over
+subroutine returns an object which encapsulates operations done over
 the objects: C<new symbolic 3> contains C<['n', 3]>, C<2 + new
 symbolic 3> contains C<['+', 2, ['n', 3]]>.
 
@@ -879,7 +1030,7 @@ circumscribed octagon using the above package:
   my $iter = 1;                        # 2**($iter+2) = 8
   my $side = new symbolic 1;
   my $cnt = $iter;
-  
+
   while ($cnt--) {
     $side = (sqrt(1 + $side**2) - 1)/$side;
   }
@@ -955,7 +1106,7 @@ compare an object to 0.  In fact, it is easier to write a numeric
 conversion routine.
 
 Here is the text of F<symbolic.pm> with such a routine added (and
-slightly modifed str()):
+slightly modified str()):
 
   package symbolic;            # Primitive symbolic calculator
   use overload
@@ -994,7 +1145,7 @@ slightly modifed str()):
   }
 
 All the work of numeric conversion is done in %subr and num().  Of
-course, %subr is not complete, it contains only operators used in teh
+course, %subr is not complete, it contains only operators used in the
 example below.  Here is the extra-credit question: why do we need an
 explicit recursion in num()?  (Answer is at the end of this section.)
 
@@ -1004,7 +1155,7 @@ Use this module like this:
   my $iter = new symbolic 2;   # 16-gon
   my $side = new symbolic 1;
   my $cnt = $iter;
-  
+
   while ($cnt) {
     $cnt = $cnt - 1;           # Mutator `--' not implemented
     $side = (sqrt(1 + $side**2) - 1)/$side;
@@ -1024,7 +1175,7 @@ mutator methods (C<++>, C<-=> and so on), does not do deep copying
 (not required without mutators!), and implements only those arithmetic
 operations which are used in the example.
 
-To implement most arithmetic operattions is easy, one should just use
+To implement most arithmetic operations is easy, one should just use
 the tables of operations, and change the code which fills %subr to
 
   my %subr = ( 'n' => sub {$_[0]} );
@@ -1102,8 +1253,8 @@ the argument of num().
 If you wonder why defaults for conversion are different for str() and
 num(), note how easy it was to write the symbolic calculator.  This
 simplicity is due to an appropriate choice of defaults.  One extra
-note: due to teh explicit recursion num() is more fragile than sym():
-we need to explicitly check for the type of $a and $b.  If componets
+note: due to the explicit recursion num() is more fragile than sym():
+we need to explicitly check for the type of $a and $b.  If components
 $a and $b happen to be of some related type, this may lead to problems.
 
 =head2 I<Really> symbolic calculator