xref: /openbsd-src/gnu/usr.bin/perl/lib/overload.pm (revision 5054e3e78af0749a9bb00ba9a024b3ee2d90290f)
1package overload;
2
3our $VERSION = '1.07';
4
5sub nil {}
6
7sub OVERLOAD {
8  $package = shift;
9  my %arg = @_;
10  my ($sub, $fb);
11  $ {$package . "::OVERLOAD"}{dummy}++; # Register with magic by touching.
12  *{$package . "::()"} = \&nil; # Make it findable via fetchmethod.
13  for (keys %arg) {
14    if ($_ eq 'fallback') {
15      $fb = $arg{$_};
16    } else {
17      $sub = $arg{$_};
18      if (not ref $sub and $sub !~ /::/) {
19	$ {$package . "::(" . $_} = $sub;
20	$sub = \&nil;
21      }
22      #print STDERR "Setting `$ {'package'}::\cO$_' to \\&`$sub'.\n";
23      *{$package . "::(" . $_} = \&{ $sub };
24    }
25  }
26  ${$package . "::()"} = $fb; # Make it findable too (fallback only).
27}
28
29sub import {
30  $package = (caller())[0];
31  # *{$package . "::OVERLOAD"} = \&OVERLOAD;
32  shift;
33  $package->overload::OVERLOAD(@_);
34}
35
36sub unimport {
37  $package = (caller())[0];
38  ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table
39  shift;
40  for (@_) {
41    if ($_ eq 'fallback') {
42      undef $ {$package . "::()"};
43    } else {
44      delete $ {$package . "::"}{"(" . $_};
45    }
46  }
47}
48
49sub Overloaded {
50  my $package = shift;
51  $package = ref $package if ref $package;
52  $package->can('()');
53}
54
55sub ov_method {
56  my $globref = shift;
57  return undef unless $globref;
58  my $sub = \&{*$globref};
59  return $sub if $sub ne \&nil;
60  return shift->can($ {*$globref});
61}
62
63sub OverloadedStringify {
64  my $package = shift;
65  $package = ref $package if ref $package;
66  #$package->can('(""')
67  ov_method mycan($package, '(""'), $package
68    or ov_method mycan($package, '(0+'), $package
69    or ov_method mycan($package, '(bool'), $package
70    or ov_method mycan($package, '(nomethod'), $package;
71}
72
73sub Method {
74  my $package = shift;
75  if(ref $package) {
76    local $@;
77    local $!;
78    require Scalar::Util;
79    $package = Scalar::Util::blessed($package);
80    return undef if !defined $package;
81  }
82  #my $meth = $package->can('(' . shift);
83  ov_method mycan($package, '(' . shift), $package;
84  #return $meth if $meth ne \&nil;
85  #return $ {*{$meth}};
86}
87
88sub AddrRef {
89  my $package = ref $_[0];
90  return "$_[0]" unless $package;
91
92  local $@;
93  local $!;
94  require Scalar::Util;
95  my $class = Scalar::Util::blessed($_[0]);
96  my $class_prefix = defined($class) ? "$class=" : "";
97  my $type = Scalar::Util::reftype($_[0]);
98  my $addr = Scalar::Util::refaddr($_[0]);
99  return sprintf("$class_prefix$type(0x%x)", $addr);
100}
101
102*StrVal = *AddrRef;
103
104sub mycan {				# Real can would leave stubs.
105  my ($package, $meth) = @_;
106
107  my $mro = mro::get_linear_isa($package);
108  foreach my $p (@$mro) {
109    my $fqmeth = $p . q{::} . $meth;
110    return \*{$fqmeth} if defined &{$fqmeth};
111  }
112
113  return undef;
114}
115
116%constants = (
117	      'integer'	  =>  0x1000, # HINT_NEW_INTEGER
118	      'float'	  =>  0x2000, # HINT_NEW_FLOAT
119	      'binary'	  =>  0x4000, # HINT_NEW_BINARY
120	      'q'	  =>  0x8000, # HINT_NEW_STRING
121	      'qr'	  => 0x10000, # HINT_NEW_RE
122	     );
123
124%ops = ( with_assign	  => "+ - * / % ** << >> x .",
125	 assign		  => "+= -= *= /= %= **= <<= >>= x= .=",
126	 num_comparison	  => "< <= >  >= == !=",
127	 '3way_comparison'=> "<=> cmp",
128	 str_comparison	  => "lt le gt ge eq ne",
129	 binary		  => '& &= | |= ^ ^=',
130	 unary		  => "neg ! ~",
131	 mutators	  => '++ --',
132	 func		  => "atan2 cos sin exp abs log sqrt int",
133	 conversion	  => 'bool "" 0+',
134	 iterators	  => '<>',
135	 dereferencing	  => '${} @{} %{} &{} *{}',
136	 matching	  => '~~',
137	 special	  => 'nomethod fallback =');
138
139use warnings::register;
140sub constant {
141  # Arguments: what, sub
142  while (@_) {
143    if (@_ == 1) {
144        warnings::warnif ("Odd number of arguments for overload::constant");
145        last;
146    }
147    elsif (!exists $constants {$_ [0]}) {
148        warnings::warnif ("`$_[0]' is not an overloadable type");
149    }
150    elsif (!ref $_ [1] || "$_[1]" !~ /(^|=)CODE\(0x[0-9a-f]+\)$/) {
151        # Can't use C<ref $_[1] eq "CODE"> above as code references can be
152        # blessed, and C<ref> would return the package the ref is blessed into.
153        if (warnings::enabled) {
154            $_ [1] = "undef" unless defined $_ [1];
155            warnings::warn ("`$_[1]' is not a code reference");
156        }
157    }
158    else {
159        $^H{$_[0]} = $_[1];
160        $^H |= $constants{$_[0]};
161    }
162    shift, shift;
163  }
164}
165
166sub remove_constant {
167  # Arguments: what, sub
168  while (@_) {
169    delete $^H{$_[0]};
170    $^H &= ~ $constants{$_[0]};
171    shift, shift;
172  }
173}
174
1751;
176
177__END__
178
179=head1 NAME
180
181overload - Package for overloading Perl operations
182
183=head1 SYNOPSIS
184
185    package SomeThing;
186
187    use overload
188	'+' => \&myadd,
189	'-' => \&mysub;
190	# etc
191    ...
192
193    package main;
194    $a = SomeThing->new( 57 );
195    $b=5+$a;
196    ...
197    if (overload::Overloaded $b) {...}
198    ...
199    $strval = overload::StrVal $b;
200
201=head1 DESCRIPTION
202
203This pragma allows overloading of Perl's operators for a class.
204To overload built-in functions, see L<perlsub/Overriding Built-in Functions> instead.
205
206=head2 Declaration of overloaded functions
207
208The compilation directive
209
210    package Number;
211    use overload
212	"+" => \&add,
213	"*=" => "muas";
214
215declares function Number::add() for addition, and method muas() in
216the "class" C<Number> (or one of its base classes)
217for the assignment form C<*=> of multiplication.
218
219Arguments of this directive come in (key, value) pairs.  Legal values
220are values legal inside a C<&{ ... }> call, so the name of a
221subroutine, a reference to a subroutine, or an anonymous subroutine
222will all work.  Note that values specified as strings are
223interpreted as methods, not subroutines.  Legal keys are listed below.
224
225The subroutine C<add> will be called to execute C<$a+$b> if $a
226is a reference to an object blessed into the package C<Number>, or if $a is
227not an object from a package with defined mathemagic addition, but $b is a
228reference to a C<Number>.  It can also be called in other situations, like
229C<$a+=7>, or C<$a++>.  See L<MAGIC AUTOGENERATION>.  (Mathemagical
230methods refer to methods triggered by an overloaded mathematical
231operator.)
232
233Since overloading respects inheritance via the @ISA hierarchy, the
234above declaration would also trigger overloading of C<+> and C<*=> in
235all the packages which inherit from C<Number>.
236
237=head2 Calling Conventions for Binary Operations
238
239The functions specified in the C<use overload ...> directive are called
240with three (in one particular case with four, see L<Last Resort>)
241arguments.  If the corresponding operation is binary, then the first
242two arguments are the two arguments of the operation.  However, due to
243general object calling conventions, the first argument should always be
244an object in the package, so in the situation of C<7+$a>, the
245order of the arguments is interchanged.  It probably does not matter
246when implementing the addition method, but whether the arguments
247are reversed is vital to the subtraction method.  The method can
248query this information by examining the third argument, which can take
249three different values:
250
251=over 7
252
253=item FALSE
254
255the order of arguments is as in the current operation.
256
257=item TRUE
258
259the arguments are reversed.
260
261=item C<undef>
262
263the current operation is an assignment variant (as in
264C<$a+=7>), but the usual function is called instead.  This additional
265information can be used to generate some optimizations.  Compare
266L<Calling Conventions for Mutators>.
267
268=back
269
270=head2 Calling Conventions for Unary Operations
271
272Unary operation are considered binary operations with the second
273argument being C<undef>.  Thus the functions that overloads C<{"++"}>
274is called with arguments C<($a,undef,'')> when $a++ is executed.
275
276=head2 Calling Conventions for Mutators
277
278Two types of mutators have different calling conventions:
279
280=over
281
282=item C<++> and C<-->
283
284The routines which implement these operators are expected to actually
285I<mutate> their arguments.  So, assuming that $obj is a reference to a
286number,
287
288  sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
289
290is an appropriate implementation of overloaded C<++>.  Note that
291
292  sub incr { ++$ {$_[0]} ; shift }
293
294is OK if used with preincrement and with postincrement. (In the case
295of postincrement a copying will be performed, see L<Copy Constructor>.)
296
297=item C<x=> and other assignment versions
298
299There is nothing special about these methods.  They may change the
300value of their arguments, and may leave it as is.  The result is going
301to be assigned to the value in the left-hand-side if different from
302this value.
303
304This allows for the same method to be used as overloaded C<+=> and
305C<+>.  Note that this is I<allowed>, but not recommended, since by the
306semantic of L<"Fallback"> Perl will call the method for C<+> anyway,
307if C<+=> is not overloaded.
308
309=back
310
311B<Warning.>  Due to the presence of assignment versions of operations,
312routines which may be called in assignment context may create
313self-referential structures.  Currently Perl will not free self-referential
314structures until cycles are C<explicitly> broken.  You may get problems
315when traversing your structures too.
316
317Say,
318
319  use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
320
321is asking for trouble, since for code C<$obj += $foo> the subroutine
322is called as C<$obj = add($obj, $foo, undef)>, or C<$obj = [\$obj,
323\$foo]>.  If using such a subroutine is an important optimization, one
324can overload C<+=> explicitly by a non-"optimized" version, or switch
325to non-optimized version if C<not defined $_[2]> (see
326L<Calling Conventions for Binary Operations>).
327
328Even if no I<explicit> assignment-variants of operators are present in
329the script, they may be generated by the optimizer.  Say, C<",$obj,"> or
330C<',' . $obj . ','> may be both optimized to
331
332  my $tmp = ',' . $obj;    $tmp .= ',';
333
334=head2 Overloadable Operations
335
336The following symbols can be specified in C<use overload> directive:
337
338=over 5
339
340=item * I<Arithmetic operations>
341
342    "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
343    "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
344
345For these operations a substituted non-assignment variant can be called if
346the assignment variant is not available.  Methods for operations C<+>,
347C<->, C<+=>, and C<-=> can be called to automatically generate
348increment and decrement methods.  The operation C<-> can be used to
349autogenerate missing methods for unary minus or C<abs>.
350
351See L<"MAGIC AUTOGENERATION">, L<"Calling Conventions for Mutators"> and
352L<"Calling Conventions for Binary Operations">) for details of these
353substitutions.
354
355=item * I<Comparison operations>
356
357    "<",  "<=", ">",  ">=", "==", "!=", "<=>",
358    "lt", "le", "gt", "ge", "eq", "ne", "cmp",
359
360If the corresponding "spaceship" variant is available, it can be
361used to substitute for the missing operation.  During C<sort>ing
362arrays, C<cmp> is used to compare values subject to C<use overload>.
363
364=item * I<Bit operations>
365
366    "&", "&=", "^", "^=", "|", "|=", "neg", "!", "~",
367
368C<neg> stands for unary minus.  If the method for C<neg> is not
369specified, it can be autogenerated using the method for
370subtraction. If the method for C<!> is not specified, it can be
371autogenerated using the methods for C<bool>, or C<"">, or C<0+>.
372
373The same remarks in L<"Arithmetic operations"> about
374assignment-variants and autogeneration apply for
375bit operations C<"&">, C<"^">, and C<"|"> as well.
376
377=item * I<Increment and decrement>
378
379    "++", "--",
380
381If undefined, addition and subtraction methods can be
382used instead.  These operations are called both in prefix and
383postfix form.
384
385=item * I<Transcendental functions>
386
387    "atan2", "cos", "sin", "exp", "abs", "log", "sqrt", "int"
388
389If C<abs> is unavailable, it can be autogenerated using methods
390for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
391
392Note that traditionally the Perl function L<int> rounds to 0, thus for
393floating-point-like types one should follow the same semantic.  If
394C<int> is unavailable, it can be autogenerated using the overloading of
395C<0+>.
396
397=item * I<Boolean, string and numeric conversion>
398
399    'bool', '""', '0+',
400
401If one or two of these operations are not overloaded, the remaining ones can
402be used instead.  C<bool> is used in the flow control operators
403(like C<while>) and for the ternary C<?:> operation.  These functions can
404return any arbitrary Perl value.  If the corresponding operation for this value
405is overloaded too, that operation will be called again with this value.
406
407As a special case if the overload returns the object itself then it will
408be used directly. An overloaded conversion returning the object is
409probably a bug, because you're likely to get something that looks like
410C<YourPackage=HASH(0x8172b34)>.
411
412=item * I<Iteration>
413
414    "<>"
415
416If not overloaded, the argument will be converted to a filehandle or
417glob (which may require a stringification).  The same overloading
418happens both for the I<read-filehandle> syntax C<E<lt>$varE<gt>> and
419I<globbing> syntax C<E<lt>${var}E<gt>>.
420
421B<BUGS> Even in list context, the iterator is currently called only
422once and with scalar context.
423
424=item * I<Matching>
425
426The key C<"~~"> allows you to override the smart matching logic used by
427the C<~~> operator and the switch construct (C<given>/C<when>).  See
428L<perlsyn/switch> and L<feature>.
429
430Unusually, overloading of the smart match operator does not automatically
431take precedence over normal smart match behaviour. In particular, in the
432following code:
433
434    package Foo;
435    use overload '~~' => 'match';
436
437    my $obj =  Foo->new();
438    $obj ~~ [ 1,2,3 ];
439
440the smart match does I<not> invoke the method call like this:
441
442    $obj->match([1,2,3],0);
443
444rather, the smart match distributive rule takes precedence, so $obj is
445smart matched against each array element in turn until a match is found,
446so you may see between one and three of these calls instead:
447
448    $obj->match(1,0);
449    $obj->match(2,0);
450    $obj->match(3,0);
451
452Consult the match table in  L<perlsyn/"Smart matching in detail"> for
453details of when overloading is invoked.
454
455=item * I<Dereferencing>
456
457    '${}', '@{}', '%{}', '&{}', '*{}'.
458
459If not overloaded, the argument will be dereferenced I<as is>, thus
460should be of correct type.  These functions should return a reference
461of correct type, or another object with overloaded dereferencing.
462
463As a special case if the overload returns the object itself then it
464will be used directly (provided it is the correct type).
465
466The dereference operators must be specified explicitly they will not be passed to
467"nomethod".
468
469=item * I<Special>
470
471    "nomethod", "fallback", "=".
472
473see L<SPECIAL SYMBOLS FOR C<use overload>>.
474
475=back
476
477See L<"Fallback"> for an explanation of when a missing method can be
478autogenerated.
479
480A computer-readable form of the above table is available in the hash
481%overload::ops, with values being space-separated lists of names:
482
483 with_assign	  => '+ - * / % ** << >> x .',
484 assign		  => '+= -= *= /= %= **= <<= >>= x= .=',
485 num_comparison	  => '< <= > >= == !=',
486 '3way_comparison'=> '<=> cmp',
487 str_comparison	  => 'lt le gt ge eq ne',
488 binary		  => '& &= | |= ^ ^=',
489 unary		  => 'neg ! ~',
490 mutators	  => '++ --',
491 func		  => 'atan2 cos sin exp abs log sqrt',
492 conversion	  => 'bool "" 0+',
493 iterators	  => '<>',
494 dereferencing	  => '${} @{} %{} &{} *{}',
495 matching	  => '~~',
496 special	  => 'nomethod fallback ='
497
498=head2 Inheritance and overloading
499
500Inheritance interacts with overloading in two ways.
501
502=over
503
504=item Strings as values of C<use overload> directive
505
506If C<value> in
507
508  use overload key => value;
509
510is a string, it is interpreted as a method name.
511
512=item Overloading of an operation is inherited by derived classes
513
514Any class derived from an overloaded class is also overloaded.  The
515set of overloaded methods is the union of overloaded methods of all
516the ancestors. If some method is overloaded in several ancestor, then
517which description will be used is decided by the usual inheritance
518rules:
519
520If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
521C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
522then the subroutine C<D::plus_sub> will be called to implement
523operation C<+> for an object in package C<A>.
524
525=back
526
527Note that since the value of the C<fallback> key is not a subroutine,
528its inheritance is not governed by the above rules.  In the current
529implementation, the value of C<fallback> in the first overloaded
530ancestor is used, but this is accidental and subject to change.
531
532=head1 SPECIAL SYMBOLS FOR C<use overload>
533
534Three keys are recognized by Perl that are not covered by the above
535description.
536
537=head2 Last Resort
538
539C<"nomethod"> should be followed by a reference to a function of four
540parameters.  If defined, it is called when the overloading mechanism
541cannot find a method for some operation.  The first three arguments of
542this function coincide with the arguments for the corresponding method if
543it were found, the fourth argument is the symbol
544corresponding to the missing method.  If several methods are tried,
545the last one is used.  Say, C<1-$a> can be equivalent to
546
547	&nomethodMethod($a,1,1,"-")
548
549if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
550C<use overload> directive.
551
552The C<"nomethod"> mechanism is I<not> used for the dereference operators
553( ${} @{} %{} &{} *{} ).
554
555
556If some operation cannot be resolved, and there is no function
557assigned to C<"nomethod">, then an exception will be raised via die()--
558unless C<"fallback"> was specified as a key in C<use overload> directive.
559
560
561=head2 Fallback
562
563The key C<"fallback"> governs what to do if a method for a particular
564operation is not found.  Three different cases are possible depending on
565the value of C<"fallback">:
566
567=over 16
568
569=item * C<undef>
570
571Perl tries to use a
572substituted method (see L<MAGIC AUTOGENERATION>).  If this fails, it
573then tries to calls C<"nomethod"> value; if missing, an exception
574will be raised.
575
576=item * TRUE
577
578The same as for the C<undef> value, but no exception is raised.  Instead,
579it silently reverts to what it would have done were there no C<use overload>
580present.
581
582=item * defined, but FALSE
583
584No autogeneration is tried.  Perl tries to call
585C<"nomethod"> value, and if this is missing, raises an exception.
586
587=back
588
589B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
590yet, see L<"Inheritance and overloading">.
591
592=head2 Copy Constructor
593
594The value for C<"="> is a reference to a function with three
595arguments, i.e., it looks like the other values in C<use
596overload>. However, it does not overload the Perl assignment
597operator. This would go against Camel hair.
598
599This operation is called in the situations when a mutator is applied
600to a reference that shares its object with some other reference, such
601as
602
603	$a=$b;
604	++$a;
605
606To make this change $a and not change $b, a copy of C<$$a> is made,
607and $a is assigned a reference to this new object.  This operation is
608done during execution of the C<++$a>, and not during the assignment,
609(so before the increment C<$$a> coincides with C<$$b>).  This is only
610done if C<++> is expressed via a method for C<'++'> or C<'+='> (or
611C<nomethod>).  Note that if this operation is expressed via C<'+'>
612a nonmutator, i.e., as in
613
614	$a=$b;
615	$a=$a+1;
616
617then C<$a> does not reference a new copy of C<$$a>, since $$a does not
618appear as lvalue when the above code is executed.
619
620If the copy constructor is required during the execution of some mutator,
621but a method for C<'='> was not specified, it can be autogenerated as a
622string copy if the object is a plain scalar or a simple assignment if it
623is not.
624
625=over 5
626
627=item B<Example>
628
629The actually executed code for
630
631	$a=$b;
632        Something else which does not modify $a or $b....
633	++$a;
634
635may be
636
637	$a=$b;
638        Something else which does not modify $a or $b....
639	$a = $a->clone(undef,"");
640        $a->incr(undef,"");
641
642if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
643C<'='> was overloaded with C<\&clone>.
644
645=back
646
647Same behaviour is triggered by C<$b = $a++>, which is consider a synonym for
648C<$b = $a; ++$a>.
649
650=head1 MAGIC AUTOGENERATION
651
652If a method for an operation is not found, and the value for  C<"fallback"> is
653TRUE or undefined, Perl tries to autogenerate a substitute method for
654the missing operation based on the defined operations.  Autogenerated method
655substitutions are possible for the following operations:
656
657=over 16
658
659=item I<Assignment forms of arithmetic operations>
660
661C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
662is not defined.
663
664=item I<Conversion operations>
665
666String, numeric, and boolean conversion are calculated in terms of one
667another if not all of them are defined.
668
669=item I<Increment and decrement>
670
671The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
672and C<$a--> in terms of C<$a-=1> and C<$a-1>.
673
674=item C<abs($a)>
675
676can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
677
678=item I<Unary minus>
679
680can be expressed in terms of subtraction.
681
682=item I<Negation>
683
684C<!> and C<not> can be expressed in terms of boolean conversion, or
685string or numerical conversion.
686
687=item I<Concatenation>
688
689can be expressed in terms of string conversion.
690
691=item I<Comparison operations>
692
693can be expressed in terms of its "spaceship" counterpart: either
694C<E<lt>=E<gt>> or C<cmp>:
695
696    <, >, <=, >=, ==, != 	in terms of <=>
697    lt, gt, le, ge, eq, ne 	in terms of cmp
698
699=item I<Iterator>
700
701    <>				in terms of builtin operations
702
703=item I<Dereferencing>
704
705    ${} @{} %{} &{} *{}		in terms of builtin operations
706
707=item I<Copy operator>
708
709can be expressed in terms of an assignment to the dereferenced value, if this
710value is a scalar and not a reference, or simply a reference assignment
711otherwise.
712
713=back
714
715=head1 Minimal set of overloaded operations
716
717Since some operations can be automatically generated from others, there is
718a minimal set of operations that need to be overloaded in order to have
719the complete set of overloaded operations at one's disposal.
720Of course, the autogenerated operations may not do exactly what the user
721expects. See L<MAGIC AUTOGENERATION> above. The minimal set is:
722
723    + - * / % ** << >> x
724    <=> cmp
725    & | ^ ~
726    atan2 cos sin exp log sqrt int
727
728Additionally, you need to define at least one of string, boolean or
729numeric conversions because any one can be used to emulate the others.
730The string conversion can also be used to emulate concatenation.
731
732=head1 Losing overloading
733
734The restriction for the comparison operation is that even if, for example,
735`C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
736function will produce only a standard logical value based on the
737numerical value of the result of `C<cmp>'.  In particular, a working
738numeric conversion is needed in this case (possibly expressed in terms of
739other conversions).
740
741Similarly, C<.=>  and C<x=> operators lose their mathemagical properties
742if the string conversion substitution is applied.
743
744When you chop() a mathemagical object it is promoted to a string and its
745mathemagical properties are lost.  The same can happen with other
746operations as well.
747
748=head1 Run-time Overloading
749
750Since all C<use> directives are executed at compile-time, the only way to
751change overloading during run-time is to
752
753    eval 'use overload "+" => \&addmethod';
754
755You can also use
756
757    eval 'no overload "+", "--", "<="';
758
759though the use of these constructs during run-time is questionable.
760
761=head1 Public functions
762
763Package C<overload.pm> provides the following public functions:
764
765=over 5
766
767=item overload::StrVal(arg)
768
769Gives string value of C<arg> as in absence of stringify overloading. If you
770are using this to get the address of a reference (useful for checking if two
771references point to the same thing) then you may be better off using
772C<Scalar::Util::refaddr()>, which is faster.
773
774=item overload::Overloaded(arg)
775
776Returns true if C<arg> is subject to overloading of some operations.
777
778=item overload::Method(obj,op)
779
780Returns C<undef> or a reference to the method that implements C<op>.
781
782=back
783
784=head1 Overloading constants
785
786For some applications, the Perl parser mangles constants too much.
787It is possible to hook into this process via C<overload::constant()>
788and C<overload::remove_constant()> functions.
789
790These functions take a hash as an argument.  The recognized keys of this hash
791are:
792
793=over 8
794
795=item integer
796
797to overload integer constants,
798
799=item float
800
801to overload floating point constants,
802
803=item binary
804
805to overload octal and hexadecimal constants,
806
807=item q
808
809to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
810strings and here-documents,
811
812=item qr
813
814to overload constant pieces of regular expressions.
815
816=back
817
818The corresponding values are references to functions which take three arguments:
819the first one is the I<initial> string form of the constant, the second one
820is how Perl interprets this constant, the third one is how the constant is used.
821Note that the initial string form does not
822contain string delimiters, and has backslashes in backslash-delimiter
823combinations stripped (thus the value of delimiter is not relevant for
824processing of this string).  The return value of this function is how this
825constant is going to be interpreted by Perl.  The third argument is undefined
826unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
827context (comes from strings, regular expressions, and single-quote HERE
828documents), it is C<tr> for arguments of C<tr>/C<y> operators,
829it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
830
831Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
832it is expected that overloaded constant strings are equipped with reasonable
833overloaded catenation operator, otherwise absurd results will result.
834Similarly, negative numbers are considered as negations of positive constants.
835
836Note that it is probably meaningless to call the functions overload::constant()
837and overload::remove_constant() from anywhere but import() and unimport() methods.
838From these methods they may be called as
839
840	sub import {
841	  shift;
842	  return unless @_;
843	  die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
844	  overload::constant integer => sub {Math::BigInt->new(shift)};
845	}
846
847=head1 IMPLEMENTATION
848
849What follows is subject to change RSN.
850
851The table of methods for all operations is cached in magic for the
852symbol table hash for the package.  The cache is invalidated during
853processing of C<use overload>, C<no overload>, new function
854definitions, and changes in @ISA. However, this invalidation remains
855unprocessed until the next C<bless>ing into the package. Hence if you
856want to change overloading structure dynamically, you'll need an
857additional (fake) C<bless>ing to update the table.
858
859(Every SVish thing has a magic queue, and magic is an entry in that
860queue.  This is how a single variable may participate in multiple
861forms of magic simultaneously.  For instance, environment variables
862regularly have two forms at once: their %ENV magic and their taint
863magic. However, the magic which implements overloading is applied to
864the stashes, which are rarely used directly, thus should not slow down
865Perl.)
866
867If an object belongs to a package using overload, it carries a special
868flag.  Thus the only speed penalty during arithmetic operations without
869overloading is the checking of this flag.
870
871In fact, if C<use overload> is not present, there is almost no overhead
872for overloadable operations, so most programs should not suffer
873measurable performance penalties.  A considerable effort was made to
874minimize the overhead when overload is used in some package, but the
875arguments in question do not belong to packages using overload.  When
876in doubt, test your speed with C<use overload> and without it.  So far
877there have been no reports of substantial speed degradation if Perl is
878compiled with optimization turned on.
879
880There is no size penalty for data if overload is not used. The only
881size penalty if overload is used in some package is that I<all> the
882packages acquire a magic during the next C<bless>ing into the
883package. This magic is three-words-long for packages without
884overloading, and carries the cache table if the package is overloaded.
885
886Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
887carried out before any operation that can imply an assignment to the
888object $a (or $b) refers to, like C<$a++>.  You can override this
889behavior by defining your own copy constructor (see L<"Copy Constructor">).
890
891It is expected that arguments to methods that are not explicitly supposed
892to be changed are constant (but this is not enforced).
893
894=head1 Metaphor clash
895
896One may wonder why the semantic of overloaded C<=> is so counter intuitive.
897If it I<looks> counter intuitive to you, you are subject to a metaphor
898clash.
899
900Here is a Perl object metaphor:
901
902I<  object is a reference to blessed data>
903
904and an arithmetic metaphor:
905
906I<  object is a thing by itself>.
907
908The I<main> problem of overloading C<=> is the fact that these metaphors
909imply different actions on the assignment C<$a = $b> if $a and $b are
910objects.  Perl-think implies that $a becomes a reference to whatever
911$b was referencing.  Arithmetic-think implies that the value of "object"
912$a is changed to become the value of the object $b, preserving the fact
913that $a and $b are separate entities.
914
915The difference is not relevant in the absence of mutators.  After
916a Perl-way assignment an operation which mutates the data referenced by $a
917would change the data referenced by $b too.  Effectively, after
918C<$a = $b> values of $a and $b become I<indistinguishable>.
919
920On the other hand, anyone who has used algebraic notation knows the
921expressive power of the arithmetic metaphor.  Overloading works hard
922to enable this metaphor while preserving the Perlian way as far as
923possible.  Since it is not possible to freely mix two contradicting
924metaphors, overloading allows the arithmetic way to write things I<as
925far as all the mutators are called via overloaded access only>.  The
926way it is done is described in L<Copy Constructor>.
927
928If some mutator methods are directly applied to the overloaded values,
929one may need to I<explicitly unlink> other values which references the
930same value:
931
932    $a = Data->new(23);
933    ...
934    $b = $a;		# $b is "linked" to $a
935    ...
936    $a = $a->clone;	# Unlink $b from $a
937    $a->increment_by(4);
938
939Note that overloaded access makes this transparent:
940
941    $a = Data->new(23);
942    $b = $a;		# $b is "linked" to $a
943    $a += 4;		# would unlink $b automagically
944
945However, it would not make
946
947    $a = Data->new(23);
948    $a = 4;		# Now $a is a plain 4, not 'Data'
949
950preserve "objectness" of $a.  But Perl I<has> a way to make assignments
951to an object do whatever you want.  It is just not the overload, but
952tie()ing interface (see L<perlfunc/tie>).  Adding a FETCH() method
953which returns the object itself, and STORE() method which changes the
954value of the object, one can reproduce the arithmetic metaphor in its
955completeness, at least for variables which were tie()d from the start.
956
957(Note that a workaround for a bug may be needed, see L<"BUGS">.)
958
959=head1 Cookbook
960
961Please add examples to what follows!
962
963=head2 Two-face scalars
964
965Put this in F<two_face.pm> in your Perl library directory:
966
967  package two_face;		# Scalars with separate string and
968                                # numeric values.
969  sub new { my $p = shift; bless [@_], $p }
970  use overload '""' => \&str, '0+' => \&num, fallback => 1;
971  sub num {shift->[1]}
972  sub str {shift->[0]}
973
974Use it as follows:
975
976  require two_face;
977  my $seven = two_face->new("vii", 7);
978  printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
979  print "seven contains `i'\n" if $seven =~ /i/;
980
981(The second line creates a scalar which has both a string value, and a
982numeric value.)  This prints:
983
984  seven=vii, seven=7, eight=8
985  seven contains `i'
986
987=head2 Two-face references
988
989Suppose you want to create an object which is accessible as both an
990array reference and a hash reference.
991
992  package two_refs;
993  use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
994  sub new {
995    my $p = shift;
996    bless \ [@_], $p;
997  }
998  sub gethash {
999    my %h;
1000    my $self = shift;
1001    tie %h, ref $self, $self;
1002    \%h;
1003  }
1004
1005  sub TIEHASH { my $p = shift; bless \ shift, $p }
1006  my %fields;
1007  my $i = 0;
1008  $fields{$_} = $i++ foreach qw{zero one two three};
1009  sub STORE {
1010    my $self = ${shift()};
1011    my $key = $fields{shift()};
1012    defined $key or die "Out of band access";
1013    $$self->[$key] = shift;
1014  }
1015  sub FETCH {
1016    my $self = ${shift()};
1017    my $key = $fields{shift()};
1018    defined $key or die "Out of band access";
1019    $$self->[$key];
1020  }
1021
1022Now one can access an object using both the array and hash syntax:
1023
1024  my $bar = two_refs->new(3,4,5,6);
1025  $bar->[2] = 11;
1026  $bar->{two} == 11 or die 'bad hash fetch';
1027
1028Note several important features of this example.  First of all, the
1029I<actual> type of $bar is a scalar reference, and we do not overload
1030the scalar dereference.  Thus we can get the I<actual> non-overloaded
1031contents of $bar by just using C<$$bar> (what we do in functions which
1032overload dereference).  Similarly, the object returned by the
1033TIEHASH() method is a scalar reference.
1034
1035Second, we create a new tied hash each time the hash syntax is used.
1036This allows us not to worry about a possibility of a reference loop,
1037which would lead to a memory leak.
1038
1039Both these problems can be cured.  Say, if we want to overload hash
1040dereference on a reference to an object which is I<implemented> as a
1041hash itself, the only problem one has to circumvent is how to access
1042this I<actual> hash (as opposed to the I<virtual> hash exhibited by the
1043overloaded dereference operator).  Here is one possible fetching routine:
1044
1045  sub access_hash {
1046    my ($self, $key) = (shift, shift);
1047    my $class = ref $self;
1048    bless $self, 'overload::dummy'; # Disable overloading of %{}
1049    my $out = $self->{$key};
1050    bless $self, $class;	# Restore overloading
1051    $out;
1052  }
1053
1054To remove creation of the tied hash on each access, one may an extra
1055level of indirection which allows a non-circular structure of references:
1056
1057  package two_refs1;
1058  use overload '%{}' => sub { ${shift()}->[1] },
1059               '@{}' => sub { ${shift()}->[0] };
1060  sub new {
1061    my $p = shift;
1062    my $a = [@_];
1063    my %h;
1064    tie %h, $p, $a;
1065    bless \ [$a, \%h], $p;
1066  }
1067  sub gethash {
1068    my %h;
1069    my $self = shift;
1070    tie %h, ref $self, $self;
1071    \%h;
1072  }
1073
1074  sub TIEHASH { my $p = shift; bless \ shift, $p }
1075  my %fields;
1076  my $i = 0;
1077  $fields{$_} = $i++ foreach qw{zero one two three};
1078  sub STORE {
1079    my $a = ${shift()};
1080    my $key = $fields{shift()};
1081    defined $key or die "Out of band access";
1082    $a->[$key] = shift;
1083  }
1084  sub FETCH {
1085    my $a = ${shift()};
1086    my $key = $fields{shift()};
1087    defined $key or die "Out of band access";
1088    $a->[$key];
1089  }
1090
1091Now if $baz is overloaded like this, then C<$baz> is a reference to a
1092reference to the intermediate array, which keeps a reference to an
1093actual array, and the access hash.  The tie()ing object for the access
1094hash is a reference to a reference to the actual array, so
1095
1096=over
1097
1098=item *
1099
1100There are no loops of references.
1101
1102=item *
1103
1104Both "objects" which are blessed into the class C<two_refs1> are
1105references to a reference to an array, thus references to a I<scalar>.
1106Thus the accessor expression C<$$foo-E<gt>[$ind]> involves no
1107overloaded operations.
1108
1109=back
1110
1111=head2 Symbolic calculator
1112
1113Put this in F<symbolic.pm> in your Perl library directory:
1114
1115  package symbolic;		# Primitive symbolic calculator
1116  use overload nomethod => \&wrap;
1117
1118  sub new { shift; bless ['n', @_] }
1119  sub wrap {
1120    my ($obj, $other, $inv, $meth) = @_;
1121    ($obj, $other) = ($other, $obj) if $inv;
1122    bless [$meth, $obj, $other];
1123  }
1124
1125This module is very unusual as overloaded modules go: it does not
1126provide any usual overloaded operators, instead it provides the L<Last
1127Resort> operator C<nomethod>.  In this example the corresponding
1128subroutine returns an object which encapsulates operations done over
1129the objects: C<< symbolic->new(3) >> contains C<['n', 3]>, C<< 2 +
1130symbolic->new(3) >> contains C<['+', 2, ['n', 3]]>.
1131
1132Here is an example of the script which "calculates" the side of
1133circumscribed octagon using the above package:
1134
1135  require symbolic;
1136  my $iter = 1;			# 2**($iter+2) = 8
1137  my $side = symbolic->new(1);
1138  my $cnt = $iter;
1139
1140  while ($cnt--) {
1141    $side = (sqrt(1 + $side**2) - 1)/$side;
1142  }
1143  print "OK\n";
1144
1145The value of $side is
1146
1147  ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
1148	               undef], 1], ['n', 1]]
1149
1150Note that while we obtained this value using a nice little script,
1151there is no simple way to I<use> this value.  In fact this value may
1152be inspected in debugger (see L<perldebug>), but only if
1153C<bareStringify> B<O>ption is set, and not via C<p> command.
1154
1155If one attempts to print this value, then the overloaded operator
1156C<""> will be called, which will call C<nomethod> operator.  The
1157result of this operator will be stringified again, but this result is
1158again of type C<symbolic>, which will lead to an infinite loop.
1159
1160Add a pretty-printer method to the module F<symbolic.pm>:
1161
1162  sub pretty {
1163    my ($meth, $a, $b) = @{+shift};
1164    $a = 'u' unless defined $a;
1165    $b = 'u' unless defined $b;
1166    $a = $a->pretty if ref $a;
1167    $b = $b->pretty if ref $b;
1168    "[$meth $a $b]";
1169  }
1170
1171Now one can finish the script by
1172
1173  print "side = ", $side->pretty, "\n";
1174
1175The method C<pretty> is doing object-to-string conversion, so it
1176is natural to overload the operator C<""> using this method.  However,
1177inside such a method it is not necessary to pretty-print the
1178I<components> $a and $b of an object.  In the above subroutine
1179C<"[$meth $a $b]"> is a catenation of some strings and components $a
1180and $b.  If these components use overloading, the catenation operator
1181will look for an overloaded operator C<.>; if not present, it will
1182look for an overloaded operator C<"">.  Thus it is enough to use
1183
1184  use overload nomethod => \&wrap, '""' => \&str;
1185  sub str {
1186    my ($meth, $a, $b) = @{+shift};
1187    $a = 'u' unless defined $a;
1188    $b = 'u' unless defined $b;
1189    "[$meth $a $b]";
1190  }
1191
1192Now one can change the last line of the script to
1193
1194  print "side = $side\n";
1195
1196which outputs
1197
1198  side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
1199
1200and one can inspect the value in debugger using all the possible
1201methods.
1202
1203Something is still amiss: consider the loop variable $cnt of the
1204script.  It was a number, not an object.  We cannot make this value of
1205type C<symbolic>, since then the loop will not terminate.
1206
1207Indeed, to terminate the cycle, the $cnt should become false.
1208However, the operator C<bool> for checking falsity is overloaded (this
1209time via overloaded C<"">), and returns a long string, thus any object
1210of type C<symbolic> is true.  To overcome this, we need a way to
1211compare an object to 0.  In fact, it is easier to write a numeric
1212conversion routine.
1213
1214Here is the text of F<symbolic.pm> with such a routine added (and
1215slightly modified str()):
1216
1217  package symbolic;		# Primitive symbolic calculator
1218  use overload
1219    nomethod => \&wrap, '""' => \&str, '0+' => \&num;
1220
1221  sub new { shift; bless ['n', @_] }
1222  sub wrap {
1223    my ($obj, $other, $inv, $meth) = @_;
1224    ($obj, $other) = ($other, $obj) if $inv;
1225    bless [$meth, $obj, $other];
1226  }
1227  sub str {
1228    my ($meth, $a, $b) = @{+shift};
1229    $a = 'u' unless defined $a;
1230    if (defined $b) {
1231      "[$meth $a $b]";
1232    } else {
1233      "[$meth $a]";
1234    }
1235  }
1236  my %subr = ( n => sub {$_[0]},
1237	       sqrt => sub {sqrt $_[0]},
1238	       '-' => sub {shift() - shift()},
1239	       '+' => sub {shift() + shift()},
1240	       '/' => sub {shift() / shift()},
1241	       '*' => sub {shift() * shift()},
1242	       '**' => sub {shift() ** shift()},
1243	     );
1244  sub num {
1245    my ($meth, $a, $b) = @{+shift};
1246    my $subr = $subr{$meth}
1247      or die "Do not know how to ($meth) in symbolic";
1248    $a = $a->num if ref $a eq __PACKAGE__;
1249    $b = $b->num if ref $b eq __PACKAGE__;
1250    $subr->($a,$b);
1251  }
1252
1253All the work of numeric conversion is done in %subr and num().  Of
1254course, %subr is not complete, it contains only operators used in the
1255example below.  Here is the extra-credit question: why do we need an
1256explicit recursion in num()?  (Answer is at the end of this section.)
1257
1258Use this module like this:
1259
1260  require symbolic;
1261  my $iter = symbolic->new(2);	# 16-gon
1262  my $side = symbolic->new(1);
1263  my $cnt = $iter;
1264
1265  while ($cnt) {
1266    $cnt = $cnt - 1;		# Mutator `--' not implemented
1267    $side = (sqrt(1 + $side**2) - 1)/$side;
1268  }
1269  printf "%s=%f\n", $side, $side;
1270  printf "pi=%f\n", $side*(2**($iter+2));
1271
1272It prints (without so many line breaks)
1273
1274  [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
1275			  [n 1]] 2]]] 1]
1276     [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1277  pi=3.182598
1278
1279The above module is very primitive.  It does not implement
1280mutator methods (C<++>, C<-=> and so on), does not do deep copying
1281(not required without mutators!), and implements only those arithmetic
1282operations which are used in the example.
1283
1284To implement most arithmetic operations is easy; one should just use
1285the tables of operations, and change the code which fills %subr to
1286
1287  my %subr = ( 'n' => sub {$_[0]} );
1288  foreach my $op (split " ", $overload::ops{with_assign}) {
1289    $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1290  }
1291  my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1292  foreach my $op (split " ", "@overload::ops{ @bins }") {
1293    $subr{$op} = eval "sub {shift() $op shift()}";
1294  }
1295  foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1296    print "defining `$op'\n";
1297    $subr{$op} = eval "sub {$op shift()}";
1298  }
1299
1300Due to L<Calling Conventions for Mutators>, we do not need anything
1301special to make C<+=> and friends work, except filling C<+=> entry of
1302%subr, and defining a copy constructor (needed since Perl has no
1303way to know that the implementation of C<'+='> does not mutate
1304the argument, compare L<Copy Constructor>).
1305
1306To implement a copy constructor, add C<< '=' => \&cpy >> to C<use overload>
1307line, and code (this code assumes that mutators change things one level
1308deep only, so recursive copying is not needed):
1309
1310  sub cpy {
1311    my $self = shift;
1312    bless [@$self], ref $self;
1313  }
1314
1315To make C<++> and C<--> work, we need to implement actual mutators,
1316either directly, or in C<nomethod>.  We continue to do things inside
1317C<nomethod>, thus add
1318
1319    if ($meth eq '++' or $meth eq '--') {
1320      @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1321      return $obj;
1322    }
1323
1324after the first line of wrap().  This is not a most effective
1325implementation, one may consider
1326
1327  sub inc { $_[0] = bless ['++', shift, 1]; }
1328
1329instead.
1330
1331As a final remark, note that one can fill %subr by
1332
1333  my %subr = ( 'n' => sub {$_[0]} );
1334  foreach my $op (split " ", $overload::ops{with_assign}) {
1335    $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1336  }
1337  my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1338  foreach my $op (split " ", "@overload::ops{ @bins }") {
1339    $subr{$op} = eval "sub {shift() $op shift()}";
1340  }
1341  foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1342    $subr{$op} = eval "sub {$op shift()}";
1343  }
1344  $subr{'++'} = $subr{'+'};
1345  $subr{'--'} = $subr{'-'};
1346
1347This finishes implementation of a primitive symbolic calculator in
134850 lines of Perl code.  Since the numeric values of subexpressions
1349are not cached, the calculator is very slow.
1350
1351Here is the answer for the exercise: In the case of str(), we need no
1352explicit recursion since the overloaded C<.>-operator will fall back
1353to an existing overloaded operator C<"">.  Overloaded arithmetic
1354operators I<do not> fall back to numeric conversion if C<fallback> is
1355not explicitly requested.  Thus without an explicit recursion num()
1356would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild
1357the argument of num().
1358
1359If you wonder why defaults for conversion are different for str() and
1360num(), note how easy it was to write the symbolic calculator.  This
1361simplicity is due to an appropriate choice of defaults.  One extra
1362note: due to the explicit recursion num() is more fragile than sym():
1363we need to explicitly check for the type of $a and $b.  If components
1364$a and $b happen to be of some related type, this may lead to problems.
1365
1366=head2 I<Really> symbolic calculator
1367
1368One may wonder why we call the above calculator symbolic.  The reason
1369is that the actual calculation of the value of expression is postponed
1370until the value is I<used>.
1371
1372To see it in action, add a method
1373
1374  sub STORE {
1375    my $obj = shift;
1376    $#$obj = 1;
1377    @$obj->[0,1] = ('=', shift);
1378  }
1379
1380to the package C<symbolic>.  After this change one can do
1381
1382  my $a = symbolic->new(3);
1383  my $b = symbolic->new(4);
1384  my $c = sqrt($a**2 + $b**2);
1385
1386and the numeric value of $c becomes 5.  However, after calling
1387
1388  $a->STORE(12);  $b->STORE(5);
1389
1390the numeric value of $c becomes 13.  There is no doubt now that the module
1391symbolic provides a I<symbolic> calculator indeed.
1392
1393To hide the rough edges under the hood, provide a tie()d interface to the
1394package C<symbolic> (compare with L<Metaphor clash>).  Add methods
1395
1396  sub TIESCALAR { my $pack = shift; $pack->new(@_) }
1397  sub FETCH { shift }
1398  sub nop {  }		# Around a bug
1399
1400(the bug is described in L<"BUGS">).  One can use this new interface as
1401
1402  tie $a, 'symbolic', 3;
1403  tie $b, 'symbolic', 4;
1404  $a->nop;  $b->nop;	# Around a bug
1405
1406  my $c = sqrt($a**2 + $b**2);
1407
1408Now numeric value of $c is 5.  After C<$a = 12; $b = 5> the numeric value
1409of $c becomes 13.  To insulate the user of the module add a method
1410
1411  sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
1412
1413Now
1414
1415  my ($a, $b);
1416  symbolic->vars($a, $b);
1417  my $c = sqrt($a**2 + $b**2);
1418
1419  $a = 3; $b = 4;
1420  printf "c5  %s=%f\n", $c, $c;
1421
1422  $a = 12; $b = 5;
1423  printf "c13  %s=%f\n", $c, $c;
1424
1425shows that the numeric value of $c follows changes to the values of $a
1426and $b.
1427
1428=head1 AUTHOR
1429
1430Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
1431
1432=head1 SEE ALSO
1433
1434The L<overloading> pragma can be used to enable or disable overloaded
1435operations within a lexical scope.
1436
1437=head1 DIAGNOSTICS
1438
1439When Perl is run with the B<-Do> switch or its equivalent, overloading
1440induces diagnostic messages.
1441
1442Using the C<m> command of Perl debugger (see L<perldebug>) one can
1443deduce which operations are overloaded (and which ancestor triggers
1444this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
1445is shown by debugger. The method C<()> corresponds to the C<fallback>
1446key (in fact a presence of this method shows that this package has
1447overloading enabled, and it is what is used by the C<Overloaded>
1448function of module C<overload>).
1449
1450The module might issue the following warnings:
1451
1452=over 4
1453
1454=item Odd number of arguments for overload::constant
1455
1456(W) The call to overload::constant contained an odd number of arguments.
1457The arguments should come in pairs.
1458
1459=item `%s' is not an overloadable type
1460
1461(W) You tried to overload a constant type the overload package is unaware of.
1462
1463=item `%s' is not a code reference
1464
1465(W) The second (fourth, sixth, ...) argument of overload::constant needs
1466to be a code reference. Either an anonymous subroutine, or a reference
1467to a subroutine.
1468
1469=back
1470
1471=head1 BUGS
1472
1473Because it is used for overloading, the per-package hash %OVERLOAD now
1474has a special meaning in Perl. The symbol table is filled with names
1475looking like line-noise.
1476
1477For the purpose of inheritance every overloaded package behaves as if
1478C<fallback> is present (possibly undefined). This may create
1479interesting effects if some package is not overloaded, but inherits
1480from two overloaded packages.
1481
1482Relation between overloading and tie()ing is broken.  Overloading is
1483triggered or not basing on the I<previous> class of tie()d value.
1484
1485This happens because the presence of overloading is checked too early,
1486before any tie()d access is attempted.  If the FETCH()ed class of the
1487tie()d value does not change, a simple workaround is to access the value
1488immediately after tie()ing, so that after this call the I<previous> class
1489coincides with the current one.
1490
1491B<Needed:> a way to fix this without a speed penalty.
1492
1493Barewords are not covered by overloaded string constants.
1494
1495This document is confusing.  There are grammos and misleading language
1496used in places.  It would seem a total rewrite is needed.
1497
1498=cut
1499
1500