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