9 $ {$package . "::OVERLOAD"}{dummy}++; # Register with magic by touching.
10 *{$package . "::()"} = \&nil; # Make it findable via fetchmethod.
12 if ($_ eq 'fallback') {
16 if (not ref $sub and $sub !~ /::/) {
17 $ {$package . "::(" . $_} = $sub;
20 #print STDERR "Setting `$ {'package'}::\cO$_' to \\&`$sub'.\n";
21 *{$package . "::(" . $_} = \&{ $sub };
24 ${$package . "::()"} = $fb; # Make it findable too (fallback only).
28 $package = (caller())[0];
29 # *{$package . "::OVERLOAD"} = \&OVERLOAD;
31 $package->overload::OVERLOAD(@_);
35 $package = (caller())[0];
36 ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table
39 if ($_ eq 'fallback') {
40 undef $ {$package . "::()"};
42 delete $ {$package . "::"}{"(" . $_};
49 $package = ref $package if ref $package;
55 return undef unless $globref;
56 my $sub = \&{*$globref};
57 return $sub if $sub ne \&nil;
58 return shift->can($ {*$globref});
61 sub OverloadedStringify {
63 $package = ref $package if ref $package;
65 ov_method mycan($package, '(""'), $package
66 or ov_method mycan($package, '(0+'), $package
67 or ov_method mycan($package, '(bool'), $package
68 or ov_method mycan($package, '(nomethod'), $package;
73 $package = ref $package if ref $package;
74 #my $meth = $package->can('(' . shift);
75 ov_method mycan($package, '(' . shift), $package;
76 #return $meth if $meth ne \&nil;
81 my $package = ref $_[0];
82 return "$_[0]" unless $package;
83 bless $_[0], overload::Fake; # Non-overloaded package
85 bless $_[0], $package; # Back
86 $package . substr $str, index $str, '=';
90 (OverloadedStringify($_[0])) ?
95 sub mycan { # Real can would leave stubs.
96 my ($package, $meth) = @_;
97 return \*{$package . "::$meth"} if defined &{$package . "::$meth"};
99 foreach $p (@{$package . "::ISA"}) {
100 my $out = mycan($p, $meth);
114 %ops = ( with_assign => "+ - * / % ** << >> x .",
115 assign => "+= -= *= /= %= **= <<= >>= x= .=",
116 str_comparison => "< <= > >= == !=",
117 '3way_comparison'=> "<=> cmp",
118 num_comparison => "lt le gt ge eq ne",
122 func => "atan2 cos sin exp abs log sqrt",
123 conversion => 'bool "" 0+',
124 special => 'nomethod fallback =');
127 # Arguments: what, sub
130 $^H |= $constants{$_[0]} | 0x20000;
135 sub remove_constant {
136 # Arguments: what, sub
139 $^H &= ~ $constants{$_[0]};
150 overload - Package for overloading perl operations
163 $a = new SomeThing 57;
166 if (overload::Overloaded $b) {...}
168 $strval = overload::StrVal $b;
172 =head2 Declaration of overloaded functions
174 The compilation directive
181 declares function Number::add() for addition, and method muas() in
182 the "class" C<Number> (or one of its base classes)
183 for the assignment form C<*=> of multiplication.
185 Arguments of this directive come in (key, value) pairs. Legal values
186 are values legal inside a C<&{ ... }> call, so the name of a
187 subroutine, a reference to a subroutine, or an anonymous subroutine
188 will all work. Note that values specified as strings are
189 interpreted as methods, not subroutines. Legal keys are listed below.
191 The subroutine C<add> will be called to execute C<$a+$b> if $a
192 is a reference to an object blessed into the package C<Number>, or if $a is
193 not an object from a package with defined mathemagic addition, but $b is a
194 reference to a C<Number>. It can also be called in other situations, like
195 C<$a+=7>, or C<$a++>. See L<MAGIC AUTOGENERATION>. (Mathemagical
196 methods refer to methods triggered by an overloaded mathematical
199 Since overloading respects inheritance via the @ISA hierarchy, the
200 above declaration would also trigger overloading of C<+> and C<*=> in
201 all the packages which inherit from C<Number>.
203 =head2 Calling Conventions for Binary Operations
205 The functions specified in the C<use overload ...> directive are called
206 with three (in one particular case with four, see L<Last Resort>)
207 arguments. If the corresponding operation is binary, then the first
208 two arguments are the two arguments of the operation. However, due to
209 general object calling conventions, the first argument should always be
210 an object in the package, so in the situation of C<7+$a>, the
211 order of the arguments is interchanged. It probably does not matter
212 when implementing the addition method, but whether the arguments
213 are reversed is vital to the subtraction method. The method can
214 query this information by examining the third argument, which can take
215 three different values:
221 the order of arguments is as in the current operation.
225 the arguments are reversed.
229 the current operation is an assignment variant (as in
230 C<$a+=7>), but the usual function is called instead. This additional
231 information can be used to generate some optimizations. Compare
232 L<Calling Conventions for Mutators>.
236 =head2 Calling Conventions for Unary Operations
238 Unary operation are considered binary operations with the second
239 argument being C<undef>. Thus the functions that overloads C<{"++"}>
240 is called with arguments C<($a,undef,'')> when $a++ is executed.
242 =head2 Calling Conventions for Mutators
244 Two types of mutators have different calling conventions:
248 =item C<++> and C<-->
250 The routines which implement these operators are expected to actually
251 I<mutate> their arguments. So, assuming that $obj is a reference to a
254 sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
256 is an appropriate implementation of overloaded C<++>. Note that
258 sub incr { ++$ {$_[0]} ; shift }
260 is OK if used with preincrement and with postincrement. (In the case
261 of postincrement a copying will be performed, see L<Copy Constructor>.)
263 =item C<x=> and other assignment versions
265 There is nothing special about these methods. They may change the
266 value of their arguments, and may leave it as is. The result is going
267 to be assigned to the value in the left-hand-side if different from
270 This allows for the same method to be used as overloaded C<+=> and
271 C<+>. Note that this is I<allowed>, but not recommended, since by the
272 semantic of L<"Fallback"> Perl will call the method for C<+> anyway,
273 if C<+=> is not overloaded.
277 B<Warning.> Due to the presense of assignment versions of operations,
278 routines which may be called in assignment context may create
279 self-referential structures. Currently Perl will not free self-referential
280 structures until cycles are C<explicitly> broken. You may get problems
281 when traversing your structures too.
285 use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
287 is asking for trouble, since for code C<$obj += $foo> the subroutine
288 is called as C<$obj = add($obj, $foo, undef)>, or C<$obj = [\$obj,
289 \$foo]>. If using such a subroutine is an important optimization, one
290 can overload C<+=> explicitly by a non-"optimized" version, or switch
291 to non-optimized version if C<not defined $_[2]> (see
292 L<Calling Conventions for Binary Operations>).
294 Even if no I<explicit> assignment-variants of operators are present in
295 the script, they may be generated by the optimizer. Say, C<",$obj,"> or
296 C<',' . $obj . ','> may be both optimized to
298 my $tmp = ',' . $obj; $tmp .= ',';
300 =head2 Overloadable Operations
302 The following symbols can be specified in C<use overload> directive:
306 =item * I<Arithmetic operations>
308 "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
309 "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
311 For these operations a substituted non-assignment variant can be called if
312 the assignment variant is not available. Methods for operations "C<+>",
313 "C<->", "C<+=>", and "C<-=>" can be called to automatically generate
314 increment and decrement methods. The operation "C<->" can be used to
315 autogenerate missing methods for unary minus or C<abs>.
317 See L<"MAGIC AUTOGENERATION">, L<"Calling Conventions for Mutators"> and
318 L<"Calling Conventions for Binary Operations">) for details of these
321 =item * I<Comparison operations>
323 "<", "<=", ">", ">=", "==", "!=", "<=>",
324 "lt", "le", "gt", "ge", "eq", "ne", "cmp",
326 If the corresponding "spaceship" variant is available, it can be
327 used to substitute for the missing operation. During C<sort>ing
328 arrays, C<cmp> is used to compare values subject to C<use overload>.
330 =item * I<Bit operations>
332 "&", "^", "|", "neg", "!", "~",
334 "C<neg>" stands for unary minus. If the method for C<neg> is not
335 specified, it can be autogenerated using the method for
336 subtraction. If the method for "C<!>" is not specified, it can be
337 autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
339 =item * I<Increment and decrement>
343 If undefined, addition and subtraction methods can be
344 used instead. These operations are called both in prefix and
347 =item * I<Transcendental functions>
349 "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
351 If C<abs> is unavailable, it can be autogenerated using methods
352 for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
354 =item * I<Boolean, string and numeric conversion>
356 "bool", "\"\"", "0+",
358 If one or two of these operations are unavailable, the remaining ones can
359 be used instead. C<bool> is used in the flow control operators
360 (like C<while>) and for the ternary "C<?:>" operation. These functions can
361 return any arbitrary Perl value. If the corresponding operation for this value
362 is overloaded too, that operation will be called again with this value.
366 "nomethod", "fallback", "=",
368 see L<SPECIAL SYMBOLS FOR C<use overload>>.
372 See L<"Fallback"> for an explanation of when a missing method can be
375 A computer-readable form of the above table is available in the hash
376 %overload::ops, with values being space-separated lists of names:
378 with_assign => '+ - * / % ** << >> x .',
379 assign => '+= -= *= /= %= **= <<= >>= x= .=',
380 str_comparison => '< <= > >= == !=',
381 '3way_comparison'=> '<=> cmp',
382 num_comparison => 'lt le gt ge eq ne',
386 func => 'atan2 cos sin exp abs log sqrt',
387 conversion => 'bool "" 0+',
388 special => 'nomethod fallback ='
390 =head2 Inheritance and overloading
392 Inheritance interacts with overloading in two ways.
396 =item Strings as values of C<use overload> directive
400 use overload key => value;
402 is a string, it is interpreted as a method name.
404 =item Overloading of an operation is inherited by derived classes
406 Any class derived from an overloaded class is also overloaded. The
407 set of overloaded methods is the union of overloaded methods of all
408 the ancestors. If some method is overloaded in several ancestor, then
409 which description will be used is decided by the usual inheritance
412 If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
413 C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
414 then the subroutine C<D::plus_sub> will be called to implement
415 operation C<+> for an object in package C<A>.
419 Note that since the value of the C<fallback> key is not a subroutine,
420 its inheritance is not governed by the above rules. In the current
421 implementation, the value of C<fallback> in the first overloaded
422 ancestor is used, but this is accidental and subject to change.
424 =head1 SPECIAL SYMBOLS FOR C<use overload>
426 Three keys are recognized by Perl that are not covered by the above
431 C<"nomethod"> should be followed by a reference to a function of four
432 parameters. If defined, it is called when the overloading mechanism
433 cannot find a method for some operation. The first three arguments of
434 this function coincide with the arguments for the corresponding method if
435 it were found, the fourth argument is the symbol
436 corresponding to the missing method. If several methods are tried,
437 the last one is used. Say, C<1-$a> can be equivalent to
439 &nomethodMethod($a,1,1,"-")
441 if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
442 C<use overload> directive.
444 If some operation cannot be resolved, and there is no function
445 assigned to C<"nomethod">, then an exception will be raised via die()--
446 unless C<"fallback"> was specified as a key in C<use overload> directive.
450 The key C<"fallback"> governs what to do if a method for a particular
451 operation is not found. Three different cases are possible depending on
452 the value of C<"fallback">:
459 substituted method (see L<MAGIC AUTOGENERATION>). If this fails, it
460 then tries to calls C<"nomethod"> value; if missing, an exception
465 The same as for the C<undef> value, but no exception is raised. Instead,
466 it silently reverts to what it would have done were there no C<use overload>
469 =item * defined, but FALSE
471 No autogeneration is tried. Perl tries to call
472 C<"nomethod"> value, and if this is missing, raises an exception.
476 B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
477 yet, see L<"Inheritance and overloading">.
479 =head2 Copy Constructor
481 The value for C<"="> is a reference to a function with three
482 arguments, i.e., it looks like the other values in C<use
483 overload>. However, it does not overload the Perl assignment
484 operator. This would go against Camel hair.
486 This operation is called in the situations when a mutator is applied
487 to a reference that shares its object with some other reference, such
493 To make this change $a and not change $b, a copy of C<$$a> is made,
494 and $a is assigned a reference to this new object. This operation is
495 done during execution of the C<++$a>, and not during the assignment,
496 (so before the increment C<$$a> coincides with C<$$b>). This is only
497 done if C<++> is expressed via a method for C<'++'> or C<'+='> (or
498 C<nomethod>). Note that if this operation is expressed via C<'+'>
499 a nonmutator, i.e., as in
504 then C<$a> does not reference a new copy of C<$$a>, since $$a does not
505 appear as lvalue when the above code is executed.
507 If the copy constructor is required during the execution of some mutator,
508 but a method for C<'='> was not specified, it can be autogenerated as a
509 string copy if the object is a plain scalar.
515 The actually executed code for
518 Something else which does not modify $a or $b....
524 Something else which does not modify $a or $b....
525 $a = $a->clone(undef,"");
528 if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
529 C<'='> was overloaded with C<\&clone>.
533 Same behaviour is triggered by C<$b = $a++>, which is consider a synonym for
536 =head1 MAGIC AUTOGENERATION
538 If a method for an operation is not found, and the value for C<"fallback"> is
539 TRUE or undefined, Perl tries to autogenerate a substitute method for
540 the missing operation based on the defined operations. Autogenerated method
541 substitutions are possible for the following operations:
545 =item I<Assignment forms of arithmetic operations>
547 C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
550 =item I<Conversion operations>
552 String, numeric, and boolean conversion are calculated in terms of one
553 another if not all of them are defined.
555 =item I<Increment and decrement>
557 The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
558 and C<$a--> in terms of C<$a-=1> and C<$a-1>.
562 can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
566 can be expressed in terms of subtraction.
570 C<!> and C<not> can be expressed in terms of boolean conversion, or
571 string or numerical conversion.
573 =item I<Concatenation>
575 can be expressed in terms of string conversion.
577 =item I<Comparison operations>
579 can be expressed in terms of its "spaceship" counterpart: either
580 C<E<lt>=E<gt>> or C<cmp>:
582 <, >, <=, >=, ==, != in terms of <=>
583 lt, gt, le, ge, eq, ne in terms of cmp
585 =item I<Copy operator>
587 can be expressed in terms of an assignment to the dereferenced value, if this
588 value is a scalar and not a reference.
592 =head1 Losing overloading
594 The restriction for the comparison operation is that even if, for example,
595 `C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
596 function will produce only a standard logical value based on the
597 numerical value of the result of `C<cmp>'. In particular, a working
598 numeric conversion is needed in this case (possibly expressed in terms of
601 Similarly, C<.=> and C<x=> operators lose their mathemagical properties
602 if the string conversion substitution is applied.
604 When you chop() a mathemagical object it is promoted to a string and its
605 mathemagical properties are lost. The same can happen with other
608 =head1 Run-time Overloading
610 Since all C<use> directives are executed at compile-time, the only way to
611 change overloading during run-time is to
613 eval 'use overload "+" => \&addmethod';
617 eval 'no overload "+", "--", "<="';
619 though the use of these constructs during run-time is questionable.
621 =head1 Public functions
623 Package C<overload.pm> provides the following public functions:
627 =item overload::StrVal(arg)
629 Gives string value of C<arg> as in absence of stringify overloading.
631 =item overload::Overloaded(arg)
633 Returns true if C<arg> is subject to overloading of some operations.
635 =item overload::Method(obj,op)
637 Returns C<undef> or a reference to the method that implements C<op>.
641 =head1 Overloading constants
643 For some application Perl parser mangles constants too much. It is possible
644 to hook into this process via overload::constant() and overload::remove_constant()
647 These functions take a hash as an argument. The recognized keys of this hash
654 to overload integer constants,
658 to overload floating point constants,
662 to overload octal and hexadecimal constants,
666 to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
667 strings and here-documents,
671 to overload constant pieces of regular expressions.
675 The corresponding values are references to functions which take three arguments:
676 the first one is the I<initial> string form of the constant, the second one
677 is how Perl interprets this constant, the third one is how the constant is used.
678 Note that the initial string form does not
679 contain string delimiters, and has backslashes in backslash-delimiter
680 combinations stripped (thus the value of delimiter is not relevant for
681 processing of this string). The return value of this function is how this
682 constant is going to be interpreted by Perl. The third argument is undefined
683 unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
684 context (comes from strings, regular expressions, and single-quote HERE
685 documents), it is C<tr> for arguments of C<tr>/C<y> operators,
686 it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
688 Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
689 it is expected that overloaded constant strings are equipped with reasonable
690 overloaded catenation operator, otherwise absurd results will result.
691 Similarly, negative numbers are considered as negations of positive constants.
693 Note that it is probably meaningless to call the functions overload::constant()
694 and overload::remove_constant() from anywhere but import() and unimport() methods.
695 From these methods they may be called as
700 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
701 overload::constant integer => sub {Math::BigInt->new(shift)};
704 B<BUGS> Currently overloaded-ness of constants does not propagate
707 =head1 IMPLEMENTATION
709 What follows is subject to change RSN.
711 The table of methods for all operations is cached in magic for the
712 symbol table hash for the package. The cache is invalidated during
713 processing of C<use overload>, C<no overload>, new function
714 definitions, and changes in @ISA. However, this invalidation remains
715 unprocessed until the next C<bless>ing into the package. Hence if you
716 want to change overloading structure dynamically, you'll need an
717 additional (fake) C<bless>ing to update the table.
719 (Every SVish thing has a magic queue, and magic is an entry in that
720 queue. This is how a single variable may participate in multiple
721 forms of magic simultaneously. For instance, environment variables
722 regularly have two forms at once: their %ENV magic and their taint
723 magic. However, the magic which implements overloading is applied to
724 the stashes, which are rarely used directly, thus should not slow down
727 If an object belongs to a package using overload, it carries a special
728 flag. Thus the only speed penalty during arithmetic operations without
729 overloading is the checking of this flag.
731 In fact, if C<use overload> is not present, there is almost no overhead
732 for overloadable operations, so most programs should not suffer
733 measurable performance penalties. A considerable effort was made to
734 minimize the overhead when overload is used in some package, but the
735 arguments in question do not belong to packages using overload. When
736 in doubt, test your speed with C<use overload> and without it. So far
737 there have been no reports of substantial speed degradation if Perl is
738 compiled with optimization turned on.
740 There is no size penalty for data if overload is not used. The only
741 size penalty if overload is used in some package is that I<all> the
742 packages acquire a magic during the next C<bless>ing into the
743 package. This magic is three-words-long for packages without
744 overloading, and carries the cache table if the package is overloaded.
746 Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
747 carried out before any operation that can imply an assignment to the
748 object $a (or $b) refers to, like C<$a++>. You can override this
749 behavior by defining your own copy constructor (see L<"Copy Constructor">).
751 It is expected that arguments to methods that are not explicitly supposed
752 to be changed are constant (but this is not enforced).
754 =head1 Metaphor clash
756 One may wonder why the semantic of overloaded C<=> is so counter intuitive.
757 If it I<looks> counter intuitive to you, you are subject to a metaphor
760 Here is a Perl object metaphor:
762 I< object is a reference to blessed data>
764 and an arithmetic metaphor:
766 I< object is a thing by itself>.
768 The I<main> problem of overloading C<=> is the fact that these metaphors
769 imply different actions on the assignment C<$a = $b> if $a and $b are
770 objects. Perl-think implies that $a becomes a reference to whatever
771 $b was referencing. Arithmetic-think implies that the value of "object"
772 $a is changed to become the value of the object $b, preserving the fact
773 that $a and $b are separate entities.
775 The difference is not relevant in the absence of mutators. After
776 a Perl-way assignment an operation which mutates the data referenced by $a
777 would change the data referenced by $b too. Effectively, after
778 C<$a = $b> values of $a and $b become I<indistinguishable>.
780 On the other hand, anyone who has used algebraic notation knows the
781 expressive power of the arithmetic metaphor. Overloading works hard
782 to enable this metaphor while preserving the Perlian way as far as
783 possible. Since it is not not possible to freely mix two contradicting
784 metaphors, overloading allows the arithmetic way to write things I<as
785 far as all the mutators are called via overloaded access only>. The
786 way it is done is described in L<Copy Constructor>.
788 If some mutator methods are directly applied to the overloaded values,
789 one may need to I<explicitly unlink> other values which references the
794 $b = $a; # $b is "linked" to $a
796 $a = $a->clone; # Unlink $b from $a
799 Note that overloaded access makes this transparent:
802 $b = $a; # $b is "linked" to $a
803 $a += 4; # would unlink $b automagically
805 However, it would not make
808 $a = 4; # Now $a is a plain 4, not 'Data'
810 preserve "objectness" of $a. But Perl I<has> a way to make assignments
811 to an object do whatever you want. It is just not the overload, but
812 tie()ing interface (see L<perlfunc/tie>). Adding a FETCH() method
813 which returns the object itself, and STORE() method which changes the
814 value of the object, one can reproduce the arithmetic metaphor in its
815 completeness, at least for variables which were tie()d from the start.
817 (Note that a workaround for a bug may be needed, see L<"BUGS">.)
821 Please add examples to what follows!
823 =head2 Two-face scalars
825 Put this in F<two_face.pm> in your Perl library directory:
827 package two_face; # Scalars with separate string and
829 sub new { my $p = shift; bless [@_], $p }
830 use overload '""' => \&str, '0+' => \&num, fallback => 1;
837 my $seven = new two_face ("vii", 7);
838 printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
839 print "seven contains `i'\n" if $seven =~ /i/;
841 (The second line creates a scalar which has both a string value, and a
842 numeric value.) This prints:
844 seven=vii, seven=7, eight=8
847 =head2 Symbolic calculator
849 Put this in F<symbolic.pm> in your Perl library directory:
851 package symbolic; # Primitive symbolic calculator
852 use overload nomethod => \&wrap;
854 sub new { shift; bless ['n', @_] }
856 my ($obj, $other, $inv, $meth) = @_;
857 ($obj, $other) = ($other, $obj) if $inv;
858 bless [$meth, $obj, $other];
861 This module is very unusual as overloaded modules go: it does not
862 provide any usual overloaded operators, instead it provides the L<Last
863 Resort> operator C<nomethod>. In this example the corresponding
864 subroutine returns an object which encapsulates operations done over
865 the objects: C<new symbolic 3> contains C<['n', 3]>, C<2 + new
866 symbolic 3> contains C<['+', 2, ['n', 3]]>.
868 Here is an example of the script which "calculates" the side of
869 circumscribed octagon using the above package:
872 my $iter = 1; # 2**($iter+2) = 8
873 my $side = new symbolic 1;
877 $side = (sqrt(1 + $side**2) - 1)/$side;
881 The value of $side is
883 ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
884 undef], 1], ['n', 1]]
886 Note that while we obtained this value using a nice little script,
887 there is no simple way to I<use> this value. In fact this value may
888 be inspected in debugger (see L<perldebug>), but ony if
889 C<bareStringify> B<O>ption is set, and not via C<p> command.
891 If one attempts to print this value, then the overloaded operator
892 C<""> will be called, which will call C<nomethod> operator. The
893 result of this operator will be stringified again, but this result is
894 again of type C<symbolic>, which will lead to an infinite loop.
896 Add a pretty-printer method to the module F<symbolic.pm>:
899 my ($meth, $a, $b) = @{+shift};
900 $a = 'u' unless defined $a;
901 $b = 'u' unless defined $b;
902 $a = $a->pretty if ref $a;
903 $b = $b->pretty if ref $b;
907 Now one can finish the script by
909 print "side = ", $side->pretty, "\n";
911 The method C<pretty> is doing object-to-string conversion, so it
912 is natural to overload the operator C<""> using this method. However,
913 inside such a method it is not necessary to pretty-print the
914 I<components> $a and $b of an object. In the above subroutine
915 C<"[$meth $a $b]"> is a catenation of some strings and components $a
916 and $b. If these components use overloading, the catenation operator
917 will look for an overloaded operator C<.>, if not present, it will
918 look for an overloaded operator C<"">. Thus it is enough to use
920 use overload nomethod => \&wrap, '""' => \&str;
922 my ($meth, $a, $b) = @{+shift};
923 $a = 'u' unless defined $a;
924 $b = 'u' unless defined $b;
928 Now one can change the last line of the script to
930 print "side = $side\n";
934 side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
936 and one can inspect the value in debugger using all the possible
939 Something is is still amiss: consider the loop variable $cnt of the
940 script. It was a number, not an object. We cannot make this value of
941 type C<symbolic>, since then the loop will not terminate.
943 Indeed, to terminate the cycle, the $cnt should become false.
944 However, the operator C<bool> for checking falsity is overloaded (this
945 time via overloaded C<"">), and returns a long string, thus any object
946 of type C<symbolic> is true. To overcome this, we need a way to
947 compare an object to 0. In fact, it is easier to write a numeric
950 Here is the text of F<symbolic.pm> with such a routine added (and
951 slightly modified str()):
953 package symbolic; # Primitive symbolic calculator
955 nomethod => \&wrap, '""' => \&str, '0+' => \#
957 sub new { shift; bless ['n', @_] }
959 my ($obj, $other, $inv, $meth) = @_;
960 ($obj, $other) = ($other, $obj) if $inv;
961 bless [$meth, $obj, $other];
964 my ($meth, $a, $b) = @{+shift};
965 $a = 'u' unless defined $a;
972 my %subr = ( n => sub {$_[0]},
973 sqrt => sub {sqrt $_[0]},
974 '-' => sub {shift() - shift()},
975 '+' => sub {shift() + shift()},
976 '/' => sub {shift() / shift()},
977 '*' => sub {shift() * shift()},
978 '**' => sub {shift() ** shift()},
981 my ($meth, $a, $b) = @{+shift};
982 my $subr = $subr{$meth}
983 or die "Do not know how to ($meth) in symbolic";
984 $a = $a->num if ref $a eq __PACKAGE__;
985 $b = $b->num if ref $b eq __PACKAGE__;
989 All the work of numeric conversion is done in %subr and num(). Of
990 course, %subr is not complete, it contains only operators used in the
991 example below. Here is the extra-credit question: why do we need an
992 explicit recursion in num()? (Answer is at the end of this section.)
994 Use this module like this:
997 my $iter = new symbolic 2; # 16-gon
998 my $side = new symbolic 1;
1002 $cnt = $cnt - 1; # Mutator `--' not implemented
1003 $side = (sqrt(1 + $side**2) - 1)/$side;
1005 printf "%s=%f\n", $side, $side;
1006 printf "pi=%f\n", $side*(2**($iter+2));
1008 It prints (without so many line breaks)
1010 [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
1012 [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1015 The above module is very primitive. It does not implement
1016 mutator methods (C<++>, C<-=> and so on), does not do deep copying
1017 (not required without mutators!), and implements only those arithmetic
1018 operations which are used in the example.
1020 To implement most arithmetic operations is easy, one should just use
1021 the tables of operations, and change the code which fills %subr to
1023 my %subr = ( 'n' => sub {$_[0]} );
1024 foreach my $op (split " ", $overload::ops{with_assign}) {
1025 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1027 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1028 foreach my $op (split " ", "@overload::ops{ @bins }") {
1029 $subr{$op} = eval "sub {shift() $op shift()}";
1031 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1032 print "defining `$op'\n";
1033 $subr{$op} = eval "sub {$op shift()}";
1036 Due to L<Calling Conventions for Mutators>, we do not need anything
1037 special to make C<+=> and friends work, except filling C<+=> entry of
1038 %subr, and defining a copy constructor (needed since Perl has no
1039 way to know that the implementation of C<'+='> does not mutate
1040 the argument, compare L<Copy Constructor>).
1042 To implement a copy constructor, add C<'=' => \&cpy> to C<use overload>
1043 line, and code (this code assumes that mutators change things one level
1044 deep only, so recursive copying is not needed):
1048 bless [@$self], ref $self;
1051 To make C<++> and C<--> work, we need to implement actual mutators,
1052 either directly, or in C<nomethod>. We continue to do things inside
1053 C<nomethod>, thus add
1055 if ($meth eq '++' or $meth eq '--') {
1056 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1060 after the first line of wrap(). This is not a most effective
1061 implementation, one may consider
1063 sub inc { $_[0] = bless ['++', shift, 1]; }
1067 As a final remark, note that one can fill %subr by
1069 my %subr = ( 'n' => sub {$_[0]} );
1070 foreach my $op (split " ", $overload::ops{with_assign}) {
1071 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1073 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1074 foreach my $op (split " ", "@overload::ops{ @bins }") {
1075 $subr{$op} = eval "sub {shift() $op shift()}";
1077 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1078 $subr{$op} = eval "sub {$op shift()}";
1080 $subr{'++'} = $subr{'+'};
1081 $subr{'--'} = $subr{'-'};
1083 This finishes implementation of a primitive symbolic calculator in
1084 50 lines of Perl code. Since the numeric values of subexpressions
1085 are not cached, the calculator is very slow.
1087 Here is the answer for the exercise: In the case of str(), we need no
1088 explicit recursion since the overloaded C<.>-operator will fall back
1089 to an existing overloaded operator C<"">. Overloaded arithmetic
1090 operators I<do not> fall back to numeric conversion if C<fallback> is
1091 not explicitly requested. Thus without an explicit recursion num()
1092 would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild
1093 the argument of num().
1095 If you wonder why defaults for conversion are different for str() and
1096 num(), note how easy it was to write the symbolic calculator. This
1097 simplicity is due to an appropriate choice of defaults. One extra
1098 note: due to the explicit recursion num() is more fragile than sym():
1099 we need to explicitly check for the type of $a and $b. If components
1100 $a and $b happen to be of some related type, this may lead to problems.
1102 =head2 I<Really> symbolic calculator
1104 One may wonder why we call the above calculator symbolic. The reason
1105 is that the actual calculation of the value of expression is postponed
1106 until the value is I<used>.
1108 To see it in action, add a method
1113 @$obj->[0,1] = ('=', shift);
1116 to the package C<symbolic>. After this change one can do
1118 my $a = new symbolic 3;
1119 my $b = new symbolic 4;
1120 my $c = sqrt($a**2 + $b**2);
1122 and the numeric value of $c becomes 5. However, after calling
1124 $a->STORE(12); $b->STORE(5);
1126 the numeric value of $c becomes 13. There is no doubt now that the module
1127 symbolic provides a I<symbolic> calculator indeed.
1129 To hide the rough edges under the hood, provide a tie()d interface to the
1130 package C<symbolic> (compare with L<Metaphor clash>). Add methods
1132 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
1134 sub nop { } # Around a bug
1136 (the bug is described in L<"BUGS">). One can use this new interface as
1138 tie $a, 'symbolic', 3;
1139 tie $b, 'symbolic', 4;
1140 $a->nop; $b->nop; # Around a bug
1142 my $c = sqrt($a**2 + $b**2);
1144 Now numeric value of $c is 5. After C<$a = 12; $b = 5> the numeric value
1145 of $c becomes 13. To insulate the user of the module add a method
1147 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
1152 symbolic->vars($a, $b);
1153 my $c = sqrt($a**2 + $b**2);
1156 printf "c5 %s=%f\n", $c, $c;
1159 printf "c13 %s=%f\n", $c, $c;
1161 shows that the numeric value of $c follows changes to the values of $a
1166 Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
1170 When Perl is run with the B<-Do> switch or its equivalent, overloading
1171 induces diagnostic messages.
1173 Using the C<m> command of Perl debugger (see L<perldebug>) one can
1174 deduce which operations are overloaded (and which ancestor triggers
1175 this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
1176 is shown by debugger. The method C<()> corresponds to the C<fallback>
1177 key (in fact a presence of this method shows that this package has
1178 overloading enabled, and it is what is used by the C<Overloaded>
1179 function of module C<overload>).
1183 Because it is used for overloading, the per-package hash %OVERLOAD now
1184 has a special meaning in Perl. The symbol table is filled with names
1185 looking like line-noise.
1187 For the purpose of inheritance every overloaded package behaves as if
1188 C<fallback> is present (possibly undefined). This may create
1189 interesting effects if some package is not overloaded, but inherits
1190 from two overloaded packages.
1192 Relation between overloading and tie()ing is broken. Overloading is
1193 triggered or not basing on the I<previous> class of tie()d value.
1195 This happens because the presence of overloading is checked too early,
1196 before any tie()d access is attempted. If the FETCH()ed class of the
1197 tie()d value does not change, a simple workaround is to access the value
1198 immediately after tie()ing, so that after this call the I<previous> class
1199 coincides with the current one.
1201 B<Needed:> a way to fix this without a speed penalty.
1203 Barewords are not covered by overloaded string constants.
1205 This document is confusing. There are grammos and misleading language
1206 used in places. It would seem a total rewrite is needed.