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