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;
170 =head1 CAVEAT SCRIPTOR
172 Overloading of operators is a subject not to be taken lightly.
173 Neither its precise implementation, syntax, nor semantics are
174 100% endorsed by Larry Wall. So any of these may be changed
175 at some point in the future.
179 =head2 Declaration of overloaded functions
181 The compilation directive
188 declares function Number::add() for addition, and method muas() in
189 the "class" C<Number> (or one of its base classes)
190 for the assignment form C<*=> of multiplication.
192 Arguments of this directive come in (key, value) pairs. Legal values
193 are values legal inside a C<&{ ... }> call, so the name of a
194 subroutine, a reference to a subroutine, or an anonymous subroutine
195 will all work. Note that values specified as strings are
196 interpreted as methods, not subroutines. Legal keys are listed below.
198 The subroutine C<add> will be called to execute C<$a+$b> if $a
199 is a reference to an object blessed into the package C<Number>, or if $a is
200 not an object from a package with defined mathemagic addition, but $b is a
201 reference to a C<Number>. It can also be called in other situations, like
202 C<$a+=7>, or C<$a++>. See L<MAGIC AUTOGENERATION>. (Mathemagical
203 methods refer to methods triggered by an overloaded mathematical
206 Since overloading respects inheritance via the @ISA hierarchy, the
207 above declaration would also trigger overloading of C<+> and C<*=> in
208 all the packages which inherit from C<Number>.
210 =head2 Calling Conventions for Binary Operations
212 The functions specified in the C<use overload ...> directive are called
213 with three (in one particular case with four, see L<Last Resort>)
214 arguments. If the corresponding operation is binary, then the first
215 two arguments are the two arguments of the operation. However, due to
216 general object calling conventions, the first argument should always be
217 an object in the package, so in the situation of C<7+$a>, the
218 order of the arguments is interchanged. It probably does not matter
219 when implementing the addition method, but whether the arguments
220 are reversed is vital to the subtraction method. The method can
221 query this information by examining the third argument, which can take
222 three different values:
228 the order of arguments is as in the current operation.
232 the arguments are reversed.
236 the current operation is an assignment variant (as in
237 C<$a+=7>), but the usual function is called instead. This additional
238 information can be used to generate some optimizations. Compare
239 L<Calling Conventions for Mutators>.
243 =head2 Calling Conventions for Unary Operations
245 Unary operation are considered binary operations with the second
246 argument being C<undef>. Thus the functions that overloads C<{"++"}>
247 is called with arguments C<($a,undef,'')> when $a++ is executed.
249 =head2 Calling Conventions for Mutators
251 Two types of mutators have different calling conventions:
255 =item C<++> and C<-->
257 The routines which implement these operators are expected to actually
258 I<mutate> their arguments. So, assuming that $obj is a reference to a
261 sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
263 is an appropriate implementation of overloaded C<++>. Note that
265 sub incr { ++$ {$_[0]} ; shift }
267 is OK if used with preincrement and with postincrement. (In the case
268 of postincrement a copying will be performed, see L<Copy Constructor>.)
270 =item C<x=> and other assignment versions
272 There is nothing special about these methods. They may change the
273 value of their arguments, and may leave it as is. The result is going
274 to be assigned to the value in the left-hand-side if different from
277 This allows for the same method to be used as averloaded C<+=> and
278 C<+>. Note that this is I<allowed>, but not recommended, since by the
279 semantic of L<"Fallback"> Perl will call the method for C<+> anyway,
280 if C<+=> is not overloaded.
284 B<Warning.> Due to the presense of assignment versions of operations,
285 routines which may be called in assignment context may create
286 self-referencial structures. Currently Perl will not free self-referential
287 structures until cycles are C<explicitly> broken. You may get problems
288 when traversing your structures too.
292 use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
294 is asking for trouble, since for code C<$obj += $foo> the subroutine
295 is called as C<$obj = add($obj, $foo, undef)>, or C<$obj = [\$obj,
296 \$foo]>. If using such a subroutine is an important optimization, one
297 can overload C<+=> explicitly by a non-"optimized" version, or switch
298 to non-optimized version if C<not defined $_[2]> (see
299 L<Calling Conventions for Binary Operations>).
301 Even if no I<explicit> assignment-variants of operators are present in
302 the script, they may be generated by the optimizer. Say, C<",$obj,"> or
303 C<',' . $obj . ','> may be both optimized to
305 my $tmp = ',' . $obj; $tmp .= ',';
307 =head2 Overloadable Operations
309 The following symbols can be specified in C<use overload> directive:
313 =item * I<Arithmetic operations>
315 "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
316 "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
318 For these operations a substituted non-assignment variant can be called if
319 the assignment variant is not available. Methods for operations "C<+>",
320 "C<->", "C<+=>", and "C<-=>" can be called to automatically generate
321 increment and decrement methods. The operation "C<->" can be used to
322 autogenerate missing methods for unary minus or C<abs>.
324 See L<"MAGIC AUTOGENERATION">, L<"Calling Conventions for Mutators"> and
325 L<"Calling Conventions for Binary Operations">) for details of these
328 =item * I<Comparison operations>
330 "<", "<=", ">", ">=", "==", "!=", "<=>",
331 "lt", "le", "gt", "ge", "eq", "ne", "cmp",
333 If the corresponding "spaceship" variant is available, it can be
334 used to substitute for the missing operation. During C<sort>ing
335 arrays, C<cmp> is used to compare values subject to C<use overload>.
337 =item * I<Bit operations>
339 "&", "^", "|", "neg", "!", "~",
341 "C<neg>" stands for unary minus. If the method for C<neg> is not
342 specified, it can be autogenerated using the method for
343 subtraction. If the method for "C<!>" is not specified, it can be
344 autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
346 =item * I<Increment and decrement>
350 If undefined, addition and subtraction methods can be
351 used instead. These operations are called both in prefix and
354 =item * I<Transcendental functions>
356 "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
358 If C<abs> is unavailable, it can be autogenerated using methods
359 for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
361 =item * I<Boolean, string and numeric conversion>
363 "bool", "\"\"", "0+",
365 If one or two of these operations are unavailable, the remaining ones can
366 be used instead. C<bool> is used in the flow control operators
367 (like C<while>) and for the ternary "C<?:>" operation. These functions can
368 return any arbitrary Perl value. If the corresponding operation for this value
369 is overloaded too, that operation will be called again with this value.
373 "nomethod", "fallback", "=",
375 see L<SPECIAL SYMBOLS FOR C<use overload>>.
379 See L<"Fallback"> for an explanation of when a missing method can be
382 A computer-readable form of the above table is available in the hash
383 %overload::ops, with values being space-separated lists of names:
385 with_assign => '+ - * / % ** << >> x .',
386 assign => '+= -= *= /= %= **= <<= >>= x= .=',
387 str_comparison => '< <= > >= == !=',
388 '3way_comparison'=> '<=> cmp',
389 num_comparison => 'lt le gt ge eq ne',
393 func => 'atan2 cos sin exp abs log sqrt',
394 conversion => 'bool "" 0+',
395 special => 'nomethod fallback ='
397 =head2 Inheritance and overloading
399 Inheritance interacts with overloading in two ways.
403 =item Strings as values of C<use overload> directive
407 use overload key => value;
409 is a string, it is interpreted as a method name.
411 =item Overloading of an operation is inherited by derived classes
413 Any class derived from an overloaded class is also overloaded. The
414 set of overloaded methods is the union of overloaded methods of all
415 the ancestors. If some method is overloaded in several ancestor, then
416 which description will be used is decided by the usual inheritance
419 If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
420 C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
421 then the subroutine C<D::plus_sub> will be called to implement
422 operation C<+> for an object in package C<A>.
426 Note that since the value of the C<fallback> key is not a subroutine,
427 its inheritance is not governed by the above rules. In the current
428 implementation, the value of C<fallback> in the first overloaded
429 ancestor is used, but this is accidental and subject to change.
431 =head1 SPECIAL SYMBOLS FOR C<use overload>
433 Three keys are recognized by Perl that are not covered by the above
438 C<"nomethod"> should be followed by a reference to a function of four
439 parameters. If defined, it is called when the overloading mechanism
440 cannot find a method for some operation. The first three arguments of
441 this function coincide with the arguments for the corresponding method if
442 it were found, the fourth argument is the symbol
443 corresponding to the missing method. If several methods are tried,
444 the last one is used. Say, C<1-$a> can be equivalent to
446 &nomethodMethod($a,1,1,"-")
448 if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
449 C<use overload> directive.
451 If some operation cannot be resolved, and there is no function
452 assigned to C<"nomethod">, then an exception will be raised via die()--
453 unless C<"fallback"> was specified as a key in C<use overload> directive.
457 The key C<"fallback"> governs what to do if a method for a particular
458 operation is not found. Three different cases are possible depending on
459 the value of C<"fallback">:
466 substituted method (see L<MAGIC AUTOGENERATION>). If this fails, it
467 then tries to calls C<"nomethod"> value; if missing, an exception
472 The same as for the C<undef> value, but no exception is raised. Instead,
473 it silently reverts to what it would have done were there no C<use overload>
476 =item * defined, but FALSE
478 No autogeneration is tried. Perl tries to call
479 C<"nomethod"> value, and if this is missing, raises an exception.
483 B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
484 yet, see L<"Inheritance and overloading">.
486 =head2 Copy Constructor
488 The value for C<"="> is a reference to a function with three
489 arguments, i.e., it looks like the other values in C<use
490 overload>. However, it does not overload the Perl assignment
491 operator. This would go against Camel hair.
493 This operation is called in the situations when a mutator is applied
494 to a reference that shares its object with some other reference, such
500 To make this change $a and not change $b, a copy of C<$$a> is made,
501 and $a is assigned a reference to this new object. This operation is
502 done during execution of the C<++$a>, and not during the assignment,
503 (so before the increment C<$$a> coincides with C<$$b>). This is only
504 done if C<++> is expressed via a method for C<'++'> or C<'+='> (or
505 C<nomethod>). Note that if this operation is expressed via C<'+'>
506 a nonmutator, i.e., as in
511 then C<$a> does not reference a new copy of C<$$a>, since $$a does not
512 appear as lvalue when the above code is executed.
514 If the copy constructor is required during the execution of some mutator,
515 but a method for C<'='> was not specified, it can be autogenerated as a
516 string copy if the object is a plain scalar.
522 The actually executed code for
525 Something else which does not modify $a or $b....
531 Something else which does not modify $a or $b....
532 $a = $a->clone(undef,"");
535 if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
536 C<'='> was overloaded with C<\&clone>.
540 Same behaviour is triggered by C<$b = $a++>, which is consider a synonim for
543 =head1 MAGIC AUTOGENERATION
545 If a method for an operation is not found, and the value for C<"fallback"> is
546 TRUE or undefined, Perl tries to autogenerate a substitute method for
547 the missing operation based on the defined operations. Autogenerated method
548 substitutions are possible for the following operations:
552 =item I<Assignment forms of arithmetic operations>
554 C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
557 =item I<Conversion operations>
559 String, numeric, and boolean conversion are calculated in terms of one
560 another if not all of them are defined.
562 =item I<Increment and decrement>
564 The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
565 and C<$a--> in terms of C<$a-=1> and C<$a-1>.
569 can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
573 can be expressed in terms of subtraction.
577 C<!> and C<not> can be expressed in terms of boolean conversion, or
578 string or numerical conversion.
580 =item I<Concatenation>
582 can be expressed in terms of string conversion.
584 =item I<Comparison operations>
586 can be expressed in terms of its "spaceship" counterpart: either
587 C<E<lt>=E<gt>> or C<cmp>:
589 <, >, <=, >=, ==, != in terms of <=>
590 lt, gt, le, ge, eq, ne in terms of cmp
592 =item I<Copy operator>
594 can be expressed in terms of an assignment to the dereferenced value, if this
595 value is a scalar and not a reference.
599 =head1 Losing overloading
601 The restriction for the comparison operation is that even if, for example,
602 `C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
603 function will produce only a standard logical value based on the
604 numerical value of the result of `C<cmp>'. In particular, a working
605 numeric conversion is needed in this case (possibly expressed in terms of
608 Similarly, C<.=> and C<x=> operators lose their mathemagical properties
609 if the string conversion substitution is applied.
611 When you chop() a mathemagical object it is promoted to a string and its
612 mathemagical properties are lost. The same can happen with other
615 =head1 Run-time Overloading
617 Since all C<use> directives are executed at compile-time, the only way to
618 change overloading during run-time is to
620 eval 'use overload "+" => \&addmethod';
624 eval 'no overload "+", "--", "<="';
626 though the use of these constructs during run-time is questionable.
628 =head1 Public functions
630 Package C<overload.pm> provides the following public functions:
634 =item overload::StrVal(arg)
636 Gives string value of C<arg> as in absence of stringify overloading.
638 =item overload::Overloaded(arg)
640 Returns true if C<arg> is subject to overloading of some operations.
642 =item overload::Method(obj,op)
644 Returns C<undef> or a reference to the method that implements C<op>.
648 =head1 Overloading constants
650 For some application Perl parser mangles constants too much. It is possible
651 to hook into this process via overload::constant() and overload::remove_constant()
654 These functions take a hash as an argument. The recognized keys of this hash
661 to overload integer constants,
665 to overload floating point constants,
669 to overload octal and hexadecimal constants,
673 to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
674 strings and here-documents,
678 to overload constant pieces of regular expressions.
682 The corresponding values are references to functions which take three arguments:
683 the first one is the I<initial> string form of the constant, the second one
684 is how Perl interprets this constant, the third one is how the constant is used.
685 Note that the initial string form does not
686 contain string delimiters, and has backslashes in backslash-delimiter
687 combinations stripped (thus the value of delimiter is not relevant for
688 processing of this string). The return value of this function is how this
689 constant is going to be interpreted by Perl. The third argument is undefined
690 unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
691 context (comes from strings, regular expressions, and single-quote HERE
692 documents), it is C<tr> for arguments of C<tr>/C<y> operators,
693 it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
695 Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
696 it is expected that overloaded constant strings are equipped with reasonable
697 overloaded catenation operator, otherwise absurd results will result.
698 Similarly, negative numbers are considered as negations of positive constants.
700 Note that it is probably meaningless to call the functions overload::constant()
701 and overload::remove_constant() from anywhere but import() and unimport() methods.
702 From these methods they may be called as
707 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
708 overload::constant integer => sub {Math::BigInt->new(shift)};
711 B<BUGS> Currently overloaded-ness of constants does not propagate
714 =head1 IMPLEMENTATION
716 What follows is subject to change RSN.
718 The table of methods for all operations is cached in magic for the
719 symbol table hash for the package. The cache is invalidated during
720 processing of C<use overload>, C<no overload>, new function
721 definitions, and changes in @ISA. However, this invalidation remains
722 unprocessed until the next C<bless>ing into the package. Hence if you
723 want to change overloading structure dynamically, you'll need an
724 additional (fake) C<bless>ing to update the table.
726 (Every SVish thing has a magic queue, and magic is an entry in that
727 queue. This is how a single variable may participate in multiple
728 forms of magic simultaneously. For instance, environment variables
729 regularly have two forms at once: their %ENV magic and their taint
730 magic. However, the magic which implements overloading is applied to
731 the stashes, which are rarely used directly, thus should not slow down
734 If an object belongs to a package using overload, it carries a special
735 flag. Thus the only speed penalty during arithmetic operations without
736 overloading is the checking of this flag.
738 In fact, if C<use overload> is not present, there is almost no overhead
739 for overloadable operations, so most programs should not suffer
740 measurable performance penalties. A considerable effort was made to
741 minimize the overhead when overload is used in some package, but the
742 arguments in question do not belong to packages using overload. When
743 in doubt, test your speed with C<use overload> and without it. So far
744 there have been no reports of substantial speed degradation if Perl is
745 compiled with optimization turned on.
747 There is no size penalty for data if overload is not used. The only
748 size penalty if overload is used in some package is that I<all> the
749 packages acquire a magic during the next C<bless>ing into the
750 package. This magic is three-words-long for packages without
751 overloading, and carries the cache tabel if the package is overloaded.
753 Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
754 carried out before any operation that can imply an assignment to the
755 object $a (or $b) refers to, like C<$a++>. You can override this
756 behavior by defining your own copy constructor (see L<"Copy Constructor">).
758 It is expected that arguments to methods that are not explicitly supposed
759 to be changed are constant (but this is not enforced).
761 =head1 Metaphor clash
763 One may wonder why the semantic of overloaded C<=> is so counterintuive.
764 If it I<looks> counterintuive to you, you are subject to a metaphor
767 Here is a Perl object metaphor:
769 I< object is a reference to blessed data>
771 and an arithmetic metaphor:
773 I< object is a thing by itself>.
775 The I<main> problem of overloading C<=> is the fact that these metaphors
776 imply different actions on the assignment C<$a = $b> if $a and $b are
777 objects. Perl-think implies that $a becomes a reference to whatever
778 $b was referencing. Arithmetic-think implies that the value of "object"
779 $a is changed to become the value of the object $b, preserving the fact
780 that $a and $b are separate entities.
782 The difference is not relevant in the absence of mutators. After
783 a Perl-way assignment an operation which mutates the data referenced by $a
784 would change the data referenced by $b too. Effectively, after
785 C<$a = $b> values of $a and $b become I<indistinguishable>.
787 On the other hand, anyone who has used algebraic notation knows the
788 expressive power of the arithmetic metaphor. Overloading works hard
789 to enable this metaphor while preserving the Perlian way as far as
790 possible. Since it is not not possible to freely mix two contradicting
791 metaphors, overloading allows the arithmetic way to write things I<as
792 far as all the mutators are called via overloaded access only>. The
793 way it is done is described in L<Copy Constructor>.
795 If some mutator methods are directly applied to the overloaded values,
796 one may need to I<explicitly unlink> other values which references the
801 $b = $a; # $b is "linked" to $a
803 $a = $a->clone; # Unlink $b from $a
806 Note that overloaded access makes this transparent:
809 $b = $a; # $b is "linked" to $a
810 $a += 4; # would unlink $b automagically
812 However, it would not make
815 $a = 4; # Now $a is a plain 4, not 'Data'
817 preserve "objectness" of $a. But Perl I<has> a way to make assignments
818 to an object do whatever you want. It is just not the overload, but
819 tie()ing interface (see L<perlfunc/tie>). Adding a FETCH() method
820 which returns the object itself, and STORE() method which changes the
821 value of the object, one can reproduce the arithmetic metaphor in its
822 completeness, at least for variables which were tie()d from the start.
824 (Note that a workaround for a bug may be needed, see L<"BUGS">.)
828 Please add examples to what follows!
830 =head2 Two-face scalars
832 Put this in F<two_face.pm> in your Perl library directory:
834 package two_face; # Scalars with separate string and
836 sub new { my $p = shift; bless [@_], $p }
837 use overload '""' => \&str, '0+' => \&num, fallback => 1;
844 my $seven = new two_face ("vii", 7);
845 printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
846 print "seven contains `i'\n" if $seven =~ /i/;
848 (The second line creates a scalar which has both a string value, and a
849 numeric value.) This prints:
851 seven=vii, seven=7, eight=8
854 =head2 Symbolic calculator
856 Put this in F<symbolic.pm> in your Perl library directory:
858 package symbolic; # Primitive symbolic calculator
859 use overload nomethod => \&wrap;
861 sub new { shift; bless ['n', @_] }
863 my ($obj, $other, $inv, $meth) = @_;
864 ($obj, $other) = ($other, $obj) if $inv;
865 bless [$meth, $obj, $other];
868 This module is very unusual as overloaded modules go: it does not
869 provide any usual overloaded operators, instead it provides the L<Last
870 Resort> operator C<nomethod>. In this example the corresponding
871 subroutine returns an object which encupsulates operations done over
872 the objects: C<new symbolic 3> contains C<['n', 3]>, C<2 + new
873 symbolic 3> contains C<['+', 2, ['n', 3]]>.
875 Here is an example of the script which "calculates" the side of
876 circumscribed octagon using the above package:
879 my $iter = 1; # 2**($iter+2) = 8
880 my $side = new symbolic 1;
884 $side = (sqrt(1 + $side**2) - 1)/$side;
888 The value of $side is
890 ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
891 undef], 1], ['n', 1]]
893 Note that while we obtained this value using a nice little script,
894 there is no simple way to I<use> this value. In fact this value may
895 be inspected in debugger (see L<perldebug>), but ony if
896 C<bareStringify> B<O>ption is set, and not via C<p> command.
898 If one attempts to print this value, then the overloaded operator
899 C<""> will be called, which will call C<nomethod> operator. The
900 result of this operator will be stringified again, but this result is
901 again of type C<symbolic>, which will lead to an infinite loop.
903 Add a pretty-printer method to the module F<symbolic.pm>:
906 my ($meth, $a, $b) = @{+shift};
907 $a = 'u' unless defined $a;
908 $b = 'u' unless defined $b;
909 $a = $a->pretty if ref $a;
910 $b = $b->pretty if ref $b;
914 Now one can finish the script by
916 print "side = ", $side->pretty, "\n";
918 The method C<pretty> is doing object-to-string conversion, so it
919 is natural to overload the operator C<""> using this method. However,
920 inside such a method it is not necessary to pretty-print the
921 I<components> $a and $b of an object. In the above subroutine
922 C<"[$meth $a $b]"> is a catenation of some strings and components $a
923 and $b. If these components use overloading, the catenation operator
924 will look for an overloaded operator C<.>, if not present, it will
925 look for an overloaded operator C<"">. Thus it is enough to use
927 use overload nomethod => \&wrap, '""' => \&str;
929 my ($meth, $a, $b) = @{+shift};
930 $a = 'u' unless defined $a;
931 $b = 'u' unless defined $b;
935 Now one can change the last line of the script to
937 print "side = $side\n";
941 side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
943 and one can inspect the value in debugger using all the possible
946 Something is is still amiss: consider the loop variable $cnt of the
947 script. It was a number, not an object. We cannot make this value of
948 type C<symbolic>, since then the loop will not terminate.
950 Indeed, to terminate the cycle, the $cnt should become false.
951 However, the operator C<bool> for checking falsity is overloaded (this
952 time via overloaded C<"">), and returns a long string, thus any object
953 of type C<symbolic> is true. To overcome this, we need a way to
954 compare an object to 0. In fact, it is easier to write a numeric
957 Here is the text of F<symbolic.pm> with such a routine added (and
958 slightly modifed str()):
960 package symbolic; # Primitive symbolic calculator
962 nomethod => \&wrap, '""' => \&str, '0+' => \#
964 sub new { shift; bless ['n', @_] }
966 my ($obj, $other, $inv, $meth) = @_;
967 ($obj, $other) = ($other, $obj) if $inv;
968 bless [$meth, $obj, $other];
971 my ($meth, $a, $b) = @{+shift};
972 $a = 'u' unless defined $a;
979 my %subr = ( n => sub {$_[0]},
980 sqrt => sub {sqrt $_[0]},
981 '-' => sub {shift() - shift()},
982 '+' => sub {shift() + shift()},
983 '/' => sub {shift() / shift()},
984 '*' => sub {shift() * shift()},
985 '**' => sub {shift() ** shift()},
988 my ($meth, $a, $b) = @{+shift};
989 my $subr = $subr{$meth}
990 or die "Do not know how to ($meth) in symbolic";
991 $a = $a->num if ref $a eq __PACKAGE__;
992 $b = $b->num if ref $b eq __PACKAGE__;
996 All the work of numeric conversion is done in %subr and num(). Of
997 course, %subr is not complete, it contains only operators used in teh
998 example below. Here is the extra-credit question: why do we need an
999 explicit recursion in num()? (Answer is at the end of this section.)
1001 Use this module like this:
1004 my $iter = new symbolic 2; # 16-gon
1005 my $side = new symbolic 1;
1009 $cnt = $cnt - 1; # Mutator `--' not implemented
1010 $side = (sqrt(1 + $side**2) - 1)/$side;
1012 printf "%s=%f\n", $side, $side;
1013 printf "pi=%f\n", $side*(2**($iter+2));
1015 It prints (without so many line breaks)
1017 [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
1019 [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1022 The above module is very primitive. It does not implement
1023 mutator methods (C<++>, C<-=> and so on), does not do deep copying
1024 (not required without mutators!), and implements only those arithmetic
1025 operations which are used in the example.
1027 To implement most arithmetic operattions is easy, one should just use
1028 the tables of operations, and change the code which fills %subr to
1030 my %subr = ( 'n' => sub {$_[0]} );
1031 foreach my $op (split " ", $overload::ops{with_assign}) {
1032 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1034 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1035 foreach my $op (split " ", "@overload::ops{ @bins }") {
1036 $subr{$op} = eval "sub {shift() $op shift()}";
1038 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1039 print "defining `$op'\n";
1040 $subr{$op} = eval "sub {$op shift()}";
1043 Due to L<Calling Conventions for Mutators>, we do not need anything
1044 special to make C<+=> and friends work, except filling C<+=> entry of
1045 %subr, and defining a copy constructor (needed since Perl has no
1046 way to know that the implementation of C<'+='> does not mutate
1047 the argument, compare L<Copy Constructor>).
1049 To implement a copy constructor, add C<'=' => \&cpy> to C<use overload>
1050 line, and code (this code assumes that mutators change things one level
1051 deep only, so recursive copying is not needed):
1055 bless [@$self], ref $self;
1058 To make C<++> and C<--> work, we need to implement actual mutators,
1059 either directly, or in C<nomethod>. We continue to do things inside
1060 C<nomethod>, thus add
1062 if ($meth eq '++' or $meth eq '--') {
1063 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1067 after the first line of wrap(). This is not a most effective
1068 implementation, one may consider
1070 sub inc { $_[0] = bless ['++', shift, 1]; }
1074 As a final remark, note that one can fill %subr by
1076 my %subr = ( 'n' => sub {$_[0]} );
1077 foreach my $op (split " ", $overload::ops{with_assign}) {
1078 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1080 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1081 foreach my $op (split " ", "@overload::ops{ @bins }") {
1082 $subr{$op} = eval "sub {shift() $op shift()}";
1084 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1085 $subr{$op} = eval "sub {$op shift()}";
1087 $subr{'++'} = $subr{'+'};
1088 $subr{'--'} = $subr{'-'};
1090 This finishes implementation of a primitive symbolic calculator in
1091 50 lines of Perl code. Since the numeric values of subexpressions
1092 are not cached, the calculator is very slow.
1094 Here is the answer for the exercise: In the case of str(), we need no
1095 explicit recursion since the overloaded C<.>-operator will fall back
1096 to an existing overloaded operator C<"">. Overloaded arithmetic
1097 operators I<do not> fall back to numeric conversion if C<fallback> is
1098 not explicitly requested. Thus without an explicit recursion num()
1099 would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild
1100 the argument of num().
1102 If you wonder why defaults for conversion are different for str() and
1103 num(), note how easy it was to write the symbolic calculator. This
1104 simplicity is due to an appropriate choice of defaults. One extra
1105 note: due to teh explicit recursion num() is more fragile than sym():
1106 we need to explicitly check for the type of $a and $b. If componets
1107 $a and $b happen to be of some related type, this may lead to problems.
1109 =head2 I<Really> symbolic calculator
1111 One may wonder why we call the above calculator symbolic. The reason
1112 is that the actual calculation of the value of expression is postponed
1113 until the value is I<used>.
1115 To see it in action, add a method
1120 @$obj->[0,1] = ('=', shift);
1123 to the package C<symbolic>. After this change one can do
1125 my $a = new symbolic 3;
1126 my $b = new symbolic 4;
1127 my $c = sqrt($a**2 + $b**2);
1129 and the numeric value of $c becomes 5. However, after calling
1131 $a->STORE(12); $b->STORE(5);
1133 the numeric value of $c becomes 13. There is no doubt now that the module
1134 symbolic provides a I<symbolic> calculator indeed.
1136 To hide the rough edges under the hood, provide a tie()d interface to the
1137 package C<symbolic> (compare with L<Metaphor clash>). Add methods
1139 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
1141 sub nop { } # Around a bug
1143 (the bug is described in L<"BUGS">). One can use this new interface as
1145 tie $a, 'symbolic', 3;
1146 tie $b, 'symbolic', 4;
1147 $a->nop; $b->nop; # Around a bug
1149 my $c = sqrt($a**2 + $b**2);
1151 Now numeric value of $c is 5. After C<$a = 12; $b = 5> the numeric value
1152 of $c becomes 13. To insulate the user of the module add a method
1154 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
1159 symbolic->vars($a, $b);
1160 my $c = sqrt($a**2 + $b**2);
1163 printf "c5 %s=%f\n", $c, $c;
1166 printf "c13 %s=%f\n", $c, $c;
1168 shows that the numeric value of $c follows changes to the values of $a
1173 Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
1177 When Perl is run with the B<-Do> switch or its equivalent, overloading
1178 induces diagnostic messages.
1180 Using the C<m> command of Perl debugger (see L<perldebug>) one can
1181 deduce which operations are overloaded (and which ancestor triggers
1182 this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
1183 is shown by debugger. The method C<()> corresponds to the C<fallback>
1184 key (in fact a presence of this method shows that this package has
1185 overloading enabled, and it is what is used by the C<Overloaded>
1186 function of module C<overload>).
1190 Because it is used for overloading, the per-package hash %OVERLOAD now
1191 has a special meaning in Perl. The symbol table is filled with names
1192 looking like line-noise.
1194 For the purpose of inheritance every overloaded package behaves as if
1195 C<fallback> is present (possibly undefined). This may create
1196 interesting effects if some package is not overloaded, but inherits
1197 from two overloaded packages.
1199 Relation between overloading and tie()ing is broken. Overloading is
1200 triggered or not basing on the I<previous> class of tie()d value.
1202 This happens because the presence of overloading is checked too early,
1203 before any tie()d access is attempted. If the FETCH()ed class of the
1204 tie()d value does not change, a simple workaround is to access the value
1205 immediately after tie()ing, so that after this call the I<previous> class
1206 coincides with the current one.
1208 B<Needed:> a way to fix this without a speed penalty.
1210 Barewords are not covered by overloaded string constants.
1212 This document is confusing. There are grammos and misleading language
1213 used in places. It would seem a total rewrite is needed.