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 ! ~ ~.",
14 func => "atan2 cos sin exp abs log sqrt int",
15 conversion => 'bool "" 0+ qr',
18 dereferencing => '${} @{} %{} &{} *{}',
20 special => 'nomethod fallback =',
24 for $category (keys %ops) {
25 $ops_seen{$_}++ for (split /\s+/, $ops{$category});
34 *{$package . "::(("} = \&nil; # Make it findable via fetchmethod.
36 if ($_ eq 'fallback') {
37 for my $sym (*{$package . "::()"}) {
38 *$sym = \&nil; # Make it findable via fetchmethod.
42 warnings::warnif("overload arg '$_' is invalid")
46 $ {$package . "::(" . $_} = $sub;
49 #print STDERR "Setting '$ {'package'}::\cO$_' to \\&'$sub'.\n";
50 *{$package . "::(" . $_} = \&{ $sub };
56 $package = (caller())[0];
57 # *{$package . "::OVERLOAD"} = \&OVERLOAD;
59 $package->overload::OVERLOAD(@_);
63 $package = (caller())[0];
65 *{$package . "::(("} = \&nil;
67 warnings::warnif("overload arg '$_' is invalid")
69 delete $ {$package . "::"}{$_ eq 'fallback' ? '()' : "(" .$_};
75 $package = ref $package if ref $package;
76 mycan ($package, '()') || mycan ($package, '((');
81 return undef unless $globref;
82 my $sub = \&{*$globref};
84 return $sub if $sub != \&nil;
85 return shift->can($ {*$globref});
88 sub OverloadedStringify {
90 $package = ref $package if ref $package;
92 ov_method mycan($package, '(""'), $package
93 or ov_method mycan($package, '(0+'), $package
94 or ov_method mycan($package, '(bool'), $package
95 or ov_method mycan($package, '(nomethod'), $package;
103 require Scalar::Util;
104 $package = Scalar::Util::blessed($package);
105 return undef if !defined $package;
107 #my $meth = $package->can('(' . shift);
108 ov_method mycan($package, '(' . shift), $package;
109 #return $meth if $meth ne \&nil;
110 #return $ {*{$meth}};
120 sub mycan { # Real can would leave stubs.
121 my ($package, $meth) = @_;
127 my $mro = mro::get_linear_isa($package);
128 foreach my $p (@$mro) {
129 my $fqmeth = $p . q{::} . $meth;
130 return \*{$fqmeth} if defined &{$fqmeth};
137 'integer' => 0x1000, # HINT_NEW_INTEGER
138 'float' => 0x2000, # HINT_NEW_FLOAT
139 'binary' => 0x4000, # HINT_NEW_BINARY
140 'q' => 0x8000, # HINT_NEW_STRING
141 'qr' => 0x10000, # HINT_NEW_RE
144 use warnings::register;
146 # Arguments: what, sub
149 warnings::warnif ("Odd number of arguments for overload::constant");
152 elsif (!exists $constants {$_ [0]}) {
153 warnings::warnif ("'$_[0]' is not an overloadable type");
155 elsif (!ref $_ [1] || "$_[1]" !~ /(^|=)CODE\(0x[0-9a-f]+\)$/) {
156 # Can't use C<ref $_[1] eq "CODE"> above as code references can be
157 # blessed, and C<ref> would return the package the ref is blessed into.
158 if (warnings::enabled) {
159 $_ [1] = "undef" unless defined $_ [1];
160 warnings::warn ("'$_[1]' is not a code reference");
165 $^H |= $constants{$_[0]};
171 sub remove_constant {
172 # Arguments: what, sub
175 $^H &= ~ $constants{$_[0]};
186 overload - Package for overloading Perl operations
199 $a = SomeThing->new( 57 );
202 if (overload::Overloaded $b) {...}
204 $strval = overload::StrVal $b;
208 This pragma allows overloading of Perl's operators for a class.
209 To overload built-in functions, see L<perlsub/Overriding Built-in Functions> instead.
215 Arguments of the C<use overload> directive are (key, value) pairs.
216 For the full set of legal keys, see L<Overloadable Operations> below.
218 Operator implementations (the values) can be subroutines,
219 references to subroutines, or anonymous subroutines
220 - in other words, anything legal inside a C<&{ ... }> call.
221 Values specified as strings are interpreted as method names.
228 '""' => sub { ...; };
230 declares that subtraction is to be implemented by method C<minus()>
231 in the class C<Number> (or one of its base classes),
232 and that the function C<Number::muas()> is to be used for the
233 assignment form of multiplication, C<*=>.
234 It also defines an anonymous subroutine to implement stringification:
235 this is called whenever an object blessed into the package C<Number>
236 is used in a string context (this subroutine might, for example,
237 return the number as a Roman numeral).
239 =head3 Calling Conventions and Magic Autogeneration
241 The following sample implementation of C<minus()> (which assumes
242 that C<Number> objects are simply blessed references to scalars)
243 illustrates the calling conventions:
247 my ($self, $other, $swap) = @_;
248 my $result = $$self - $other; # *
249 $result = -$result if $swap;
250 ref $result ? $result : bless \$result;
252 # * may recurse once - see table below
254 Three arguments are passed to all subroutines specified in the
255 C<use overload> directive (with exceptions - see below, particularly
258 The first of these is the operand providing the overloaded
259 operator implementation -
260 in this case, the object whose C<minus()> method is being called.
262 The second argument is the other operand, or C<undef> in the
263 case of a unary operator.
265 The third argument is set to TRUE if (and only if) the two
266 operands have been swapped. Perl may do this to ensure that the
267 first argument (C<$self>) is an object implementing the overloaded
268 operation, in line with general object calling conventions.
269 For example, if C<$x> and C<$y> are C<Number>s:
271 operation | generates a call to
272 ============|======================
273 $x - $y | minus($x, $y, '')
274 $x - 7 | minus($x, 7, '')
275 7 - $x | minus($x, 7, 1)
277 Perl may also use C<minus()> to implement other operators which
278 have not been specified in the C<use overload> directive,
279 according to the rules for L<Magic Autogeneration> described later.
280 For example, the C<use overload> above declared no subroutine
281 for any of the operators C<-->, C<neg> (the overload key for
282 unary minus), or C<-=>. Thus
284 operation | generates a call to
285 ============|======================
286 -$x | minus($x, 0, 1)
287 $x-- | minus($x, 1, undef)
288 $x -= 3 | minus($x, 3, undef)
291 where autogeneration results in the method for a standard
292 operator which does not change either of its operands, such
293 as C<->, being used to implement an operator which changes
294 the operand ("mutators": here, C<--> and C<-=>),
295 Perl passes undef as the third argument.
296 This still evaluates as FALSE, consistent with the fact that
297 the operands have not been swapped, but gives the subroutine
298 a chance to alter its behaviour in these cases.
300 In all the above examples, C<minus()> is required
301 only to return the result of the subtraction:
302 Perl takes care of the assignment to $x.
303 In fact, such methods should I<not> modify their operands,
304 even if C<undef> is passed as the third argument
305 (see L<Overloadable Operations>).
307 The same is not true of implementations of C<++> and C<-->:
308 these are expected to modify their operand.
309 An appropriate implementation of C<--> might look like
311 use overload '--' => "decr",
313 sub decr { --${$_[0]}; }
315 If the experimental "bitwise" feature is enabled (see L<feature>), a fifth
316 TRUE argument is passed to subroutines handling C<&>, C<|>, C<^> and C<~>.
317 This indicates that the caller is expecting numeric behaviour. The fourth
318 argument will be C<undef>, as that position (C<$_[3]>) is reserved for use
321 =head3 Mathemagic, Mutators, and Copy Constructors
323 The term 'mathemagic' describes the overloaded implementation
324 of mathematical operators.
325 Mathemagical operations raise an issue.
331 If C<$a> and C<$b> are scalars then after these statements
335 An object, however, is a reference to blessed data, so if
336 C<$a> and C<$b> are objects then the assignment C<$a = $b>
337 copies only the reference, leaving C<$a> and C<$b> referring
338 to the same object data.
339 One might therefore expect the operation C<--$a> to decrement
340 C<$b> as well as C<$a>.
341 However, this would not be consistent with how we expect the
342 mathematical operators to work.
344 Perl resolves this dilemma by transparently calling a copy
345 constructor before calling a method defined to implement
346 a mutator (C<-->, C<+=>, and so on.).
347 In the above example, when Perl reaches the decrement
348 statement, it makes a copy of the object data in C<$a> and
349 assigns to C<$a> a reference to the copied data.
350 Only then does it call C<decr()>, which alters the copied
351 data, leaving C<$b> unchanged.
352 Thus the object metaphor is preserved as far as possible,
353 while mathemagical operations still work according to the
356 Note: the preceding paragraph describes what happens when
357 Perl autogenerates the copy constructor for an object based
359 For other cases, see L<Copy Constructor>.
361 =head2 Overloadable Operations
363 The complete list of keys that can be specified in the C<use overload>
364 directive are given, separated by spaces, in the values of the
365 hash C<%overload::ops>:
367 with_assign => '+ - * / % ** << >> x .',
368 assign => '+= -= *= /= %= **= <<= >>= x= .=',
369 num_comparison => '< <= > >= == !=',
370 '3way_comparison'=> '<=> cmp',
371 str_comparison => 'lt le gt ge eq ne',
372 binary => '& &= | |= ^ ^= &. &.= |. |.= ^. ^.=',
373 unary => 'neg ! ~ ~.',
375 func => 'atan2 cos sin exp abs log sqrt int',
376 conversion => 'bool "" 0+ qr',
379 dereferencing => '${} @{} %{} &{} *{}',
381 special => 'nomethod fallback ='
383 Most of the overloadable operators map one-to-one to these keys.
384 Exceptions, including additional overloadable operations not
385 apparent from this hash, are included in the notes which follow.
386 This list is subject to growth over time.
388 A warning is issued if an attempt is made to register an operator not found
395 The operator C<not> is not a valid key for C<use overload>.
396 However, if the operator C<!> is overloaded then the same
397 implementation will be used for C<not>
398 (since the two operators differ only in precedence).
402 The key C<neg> is used for unary minus to disambiguate it from
407 Assuming they are to behave analogously to Perl's C<++> and C<-->,
408 overloaded implementations of these operators are required to
409 mutate their operands.
411 No distinction is made between prefix and postfix forms of the
412 increment and decrement operators: these differ only in the
413 point at which Perl calls the associated subroutine when
414 evaluating an expression.
416 =item * I<Assignments>
418 += -= *= /= %= **= <<= >>= x= .=
421 Simple assignment is not overloadable (the C<'='> key is used
422 for the L<Copy Constructor>).
423 Perl does have a way to make assignments to an object do whatever
424 you want, but this involves using tie(), not overload -
425 see L<perlfunc/tie> and the L</COOKBOOK> examples below.
427 The subroutine for the assignment variant of an operator is
428 required only to return the result of the operation.
429 It is permitted to change the value of its operand
430 (this is safe because Perl calls the copy constructor first),
431 but this is optional since Perl assigns the returned value to
432 the left-hand operand anyway.
434 An object that overloads an assignment operator does so only in
435 respect of assignments to that object.
436 In other words, Perl never calls the corresponding methods with
437 the third argument (the "swap" argument) set to TRUE.
438 For example, the operation
442 cannot lead to C<$b>'s implementation of C<*=> being called,
443 even if C<$a> is a scalar.
444 (It can, however, generate a call to C<$b>'s method for C<*>).
446 =item * I<Non-mutators with a mutator variant>
448 + - * / % ** << >> x .
451 As described L<above|"Calling Conventions and Magic Autogeneration">,
452 Perl may call methods for operators like C<+> and C<&> in the course
453 of implementing missing operations like C<++>, C<+=>, and C<&=>.
454 While these methods may detect this usage by testing the definedness
455 of the third argument, they should in all cases avoid changing their
457 This is because Perl does not call the copy constructor before
458 invoking these methods.
462 Traditionally, the Perl function C<int> rounds to 0
463 (see L<perlfunc/int>), and so for floating-point-like types one
464 should follow the same semantic.
466 =item * I<String, numeric, boolean, and regexp conversions>
470 These conversions are invoked according to context as necessary.
471 For example, the subroutine for C<'""'> (stringify) may be used
472 where the overloaded object is passed as an argument to C<print>,
473 and that for C<'bool'> where it is tested in the condition of a flow
474 control statement (like C<while>) or the ternary C<?:> operation.
476 Of course, in contexts like, for example, C<$obj + 1>, Perl will
477 invoke C<$obj>'s implementation of C<+> rather than (in this
478 example) converting C<$obj> to a number using the numify method
479 C<'0+'> (an exception to this is when no method has been provided
480 for C<'+'> and L</fallback> is set to TRUE).
482 The subroutines for C<'""'>, C<'0+'>, and C<'bool'> can return
483 any arbitrary Perl value.
484 If the corresponding operation for this value is overloaded too,
485 the operation will be called again with this value.
487 As a special case if the overload returns the object itself then it will
488 be used directly. An overloaded conversion returning the object is
489 probably a bug, because you're likely to get something that looks like
490 C<YourPackage=HASH(0x8172b34)>.
494 The subroutine for C<'qr'> is used wherever the object is
495 interpolated into or used as a regexp, including when it
496 appears on the RHS of a C<=~> or C<!~> operator.
498 C<qr> must return a compiled regexp, or a ref to a compiled regexp
499 (such as C<qr//> returns), and any further overloading on the return
500 value will be ignored.
504 If C<E<lt>E<gt>> is overloaded then the same implementation is used
505 for both the I<read-filehandle> syntax C<E<lt>$varE<gt>> and
506 I<globbing> syntax C<E<lt>${var}E<gt>>.
508 =item * I<File tests>
510 The key C<'-X'> is used to specify a subroutine to handle all the
511 filetest operators (C<-f>, C<-x>, and so on: see L<perlfunc/-X> for
513 it is not possible to overload any filetest operator individually.
514 To distinguish them, the letter following the '-' is passed as the
515 second argument (that is, in the slot that for binary operators
516 is used to pass the second operand).
518 Calling an overloaded filetest operator does not affect the stat value
519 associated with the special filehandle C<_>. It still refers to the
520 result of the last C<stat>, C<lstat> or unoverloaded filetest.
522 This overload was introduced in Perl 5.12.
526 The key C<"~~"> allows you to override the smart matching logic used by
527 the C<~~> operator and the switch construct (C<given>/C<when>). See
528 L<perlsyn/Switch Statements> and L<feature>.
530 Unusually, the overloaded implementation of the smart match operator
531 does not get full control of the smart match behaviour.
532 In particular, in the following code:
535 use overload '~~' => 'match';
537 my $obj = Foo->new();
540 the smart match does I<not> invoke the method call like this:
542 $obj->match([1,2,3],0);
544 rather, the smart match distributive rule takes precedence, so $obj is
545 smart matched against each array element in turn until a match is found,
546 so you may see between one and three of these calls instead:
552 Consult the match table in L<perlop/"Smartmatch Operator"> for
553 details of when overloading is invoked.
555 =item * I<Dereferencing>
559 If these operators are not explicitly overloaded then they
560 work in the normal way, yielding the underlying scalar,
561 array, or whatever stores the object data (or the appropriate
562 error message if the dereference operator doesn't match it).
563 Defining a catch-all C<'nomethod'> (see L<below|/nomethod>)
564 makes no difference to this as the catch-all function will
565 not be called to implement a missing dereference operator.
567 If a dereference operator is overloaded then it must return a
568 I<reference> of the appropriate type (for example, the
569 subroutine for key C<'${}'> should return a reference to a
570 scalar, not a scalar), or another object which overloads the
571 operator: that is, the subroutine only determines what is
572 dereferenced and the actual dereferencing is left to Perl.
573 As a special case, if the subroutine returns the object itself
574 then it will not be called again - avoiding infinite recursion.
580 See L<Special Keys for C<use overload>>.
584 =head2 Magic Autogeneration
586 If a method for an operation is not found then Perl tries to
587 autogenerate a substitute implementation from the operations
588 that have been defined.
590 Note: the behaviour described in this section can be disabled
591 by setting C<fallback> to FALSE (see L</fallback>).
593 In the following tables, numbers indicate priority.
594 For example, the table below states that,
595 if no implementation for C<'!'> has been defined then Perl will
596 implement it using C<'bool'> (that is, by inverting the value
597 returned by the method for C<'bool'>);
598 if boolean conversion is also unimplemented then Perl will
599 use C<'0+'> or, failing that, C<'""'>.
601 operator | can be autogenerated from
604 =========|==========================
618 Note: The iterator (C<'E<lt>E<gt>'>) and file test (C<'-X'>)
619 operators work as normal: if the operand is not a blessed glob or
620 IO reference then it is converted to a string (using the method
621 for C<'""'>, C<'0+'>, or C<'bool'>) to be interpreted as a glob
624 operator | can be autogenerated from
627 =========|==========================
631 abs | a1 a2 b1 b2 [*]
639 * one from [a1, a2] and one from [b1, b2]
641 Just as numeric comparisons can be autogenerated from the method
642 for C<< '<=>' >>, string comparisons can be autogenerated from
645 operators | can be autogenerated from
646 ====================|===========================
647 lt gt le ge eq ne | cmp
649 Similarly, autogeneration for keys C<'+='> and C<'++'> is analogous
650 to C<'-='> and C<'--'> above:
652 operator | can be autogenerated from
655 =========|==========================
659 And other assignment variations are analogous to
660 C<'+='> and C<'-='> (and similar to C<'.='> and C<'x='> above):
662 operator || *= /= %= **= <<= >>= &= ^= |= &.= ^.= |.=
663 -------------------||-------------------------------------------
664 autogenerated from || * / % ** << >> & ^ | &. ^. |.
666 Note also that the copy constructor (key C<'='>) may be
667 autogenerated, but only for objects based on scalars.
668 See L<Copy Constructor>.
670 =head3 Minimal Set of Overloaded Operations
672 Since some operations can be automatically generated from others, there is
673 a minimal set of operations that need to be overloaded in order to have
674 the complete set of overloaded operations at one's disposal.
675 Of course, the autogenerated operations may not do exactly what the user
676 expects. The minimal set is:
681 atan2 cos sin exp log sqrt int
685 Of the conversions, only one of string, boolean or numeric is
686 needed because each can be generated from either of the other two.
688 =head2 Special Keys for C<use overload>
692 The C<'nomethod'> key is used to specify a catch-all function to
693 be called for any operator that is not individually overloaded.
694 The specified function will be passed four parameters.
695 The first three arguments coincide with those that would have been
696 passed to the corresponding method if it had been defined.
697 The fourth argument is the C<use overload> key for that missing
698 method. If the experimental "bitwise" feature is enabled (see L<feature>),
699 a fifth TRUE argument is passed to subroutines handling C<&>, C<|>, C<^> and C<~> to indicate that the caller is expecting numeric behaviour.
701 For example, if C<$a> is an object blessed into a package declaring
703 use overload 'nomethod' => 'catch_all', # ...
709 could (unless a method is specifically declared for the key
710 C<'+'>) result in a call
712 catch_all($a, 3, 1, '+')
714 See L<How Perl Chooses an Operator Implementation>.
718 The value assigned to the key C<'fallback'> tells Perl how hard
719 it should try to find an alternative way to implement a missing
724 =item * defined, but FALSE
726 use overload "fallback" => 0, # ... ;
728 This disables L<Magic Autogeneration>.
732 In the default case where no value is explicitly assigned to
733 C<fallback>, magic autogeneration is enabled.
737 The same as for C<undef>, but if a missing operator cannot be
738 autogenerated then, instead of issuing an error message, Perl
739 is allowed to revert to what it would have done for that
740 operator if there had been no C<use overload> directive.
742 Note: in most cases, particularly the L<Copy Constructor>,
743 this is unlikely to be appropriate behaviour.
747 See L<How Perl Chooses an Operator Implementation>.
749 =head3 Copy Constructor
751 As mentioned L<above|"Mathemagic, Mutators, and Copy Constructors">,
752 this operation is called when a mutator is applied to a reference
753 that shares its object with some other reference.
754 For example, if C<$b> is mathemagical, and C<'++'> is overloaded
755 with C<'incr'>, and C<'='> is overloaded with C<'clone'>, then the
759 # ... (other code which does not modify $a or $b) ...
762 would be executed in a manner equivalent to
766 $b = $b->clone(undef, "");
775 The subroutine for C<'='> does not overload the Perl assignment
776 operator: it is used only to allow mutators to work as described
777 here. (See L</Assignments> above.)
781 As for other operations, the subroutine implementing '=' is passed
782 three arguments, though the last two are always C<undef> and C<''>.
786 The copy constructor is called only before a call to a function
787 declared to implement a mutator, for example, if C<++$b;> in the
788 code above is effected via a method declared for key C<'++'>
789 (or 'nomethod', passed C<'++'> as the fourth argument) or, by
790 autogeneration, C<'+='>.
791 It is not called if the increment operation is effected by a call
792 to the method for C<'+'> since, in the equivalent code,
797 the data referred to by C<$a> is unchanged by the assignment to
798 C<$b> of a reference to new object data.
802 The copy constructor is not called if Perl determines that it is
803 unnecessary because there is no other reference to the data being
808 If C<'fallback'> is undefined or TRUE then a copy constructor
809 can be autogenerated, but only for objects based on scalars.
810 In other cases it needs to be defined explicitly.
811 Where an object's data is stored as, for example, an array of
812 scalars, the following might be appropriate:
814 use overload '=' => sub { bless [ @{$_[0]} ] }, # ...
818 If C<'fallback'> is TRUE and no copy constructor is defined then,
819 for objects not based on scalars, Perl may silently fall back on
820 simple assignment - that is, assignment of the object reference.
821 In effect, this disables the copy constructor mechanism since
822 no new copy of the object data is created.
823 This is almost certainly not what you want.
824 (It is, however, consistent: for example, Perl's fallback for the
825 C<++> operator is to increment the reference itself.)
829 =head2 How Perl Chooses an Operator Implementation
831 Which is checked first, C<nomethod> or C<fallback>?
832 If the two operands of an operator are of different types and
833 both overload the operator, which implementation is used?
834 The following are the precedence rules:
840 If the first operand has declared a subroutine to overload the
841 operator then use that implementation.
845 Otherwise, if fallback is TRUE or undefined for the
846 first operand then see if the
847 L<rules for autogeneration|"Magic Autogeneration">
848 allows another of its operators to be used instead.
852 Unless the operator is an assignment (C<+=>, C<-=>, etc.),
853 repeat step (1) in respect of the second operand.
857 Repeat Step (2) in respect of the second operand.
861 If the first operand has a "nomethod" method then use that.
865 If the second operand has a "nomethod" method then use that.
869 If C<fallback> is TRUE for both operands
870 then perform the usual operation for the operator,
871 treating the operands as numbers, strings, or booleans
872 as appropriate for the operator (see note).
876 Nothing worked - die.
880 Where there is only one operand (or only one operand with
881 overloading) the checks in respect of the other operand above are
884 There are exceptions to the above rules for dereference operations
885 (which, if Step 1 fails, always fall back to the normal, built-in
886 implementations - see Dereferencing), and for C<~~> (which has its
887 own set of rules - see C<Matching> under L</Overloadable Operations>
890 Note on Step 7: some operators have a different semantic depending
891 on the type of their operands.
892 As there is no way to instruct Perl to treat the operands as, e.g.,
893 numbers instead of strings, the result here may not be what you
895 See L<BUGS AND PITFALLS>.
897 =head2 Losing Overloading
899 The restriction for the comparison operation is that even if, for example,
900 C<cmp> should return a blessed reference, the autogenerated C<lt>
901 function will produce only a standard logical value based on the
902 numerical value of the result of C<cmp>. In particular, a working
903 numeric conversion is needed in this case (possibly expressed in terms of
906 Similarly, C<.=> and C<x=> operators lose their mathemagical properties
907 if the string conversion substitution is applied.
909 When you chop() a mathemagical object it is promoted to a string and its
910 mathemagical properties are lost. The same can happen with other
913 =head2 Inheritance and Overloading
915 Overloading respects inheritance via the @ISA hierarchy.
916 Inheritance interacts with overloading in two ways.
920 =item Method names in the C<use overload> directive
924 use overload key => value;
926 is a string, it is interpreted as a method name - which may
927 (in the usual way) be inherited from another class.
929 =item Overloading of an operation is inherited by derived classes
931 Any class derived from an overloaded class is also overloaded
932 and inherits its operator implementations.
933 If the same operator is overloaded in more than one ancestor
934 then the implementation is determined by the usual inheritance
937 For example, if C<A> inherits from C<B> and C<C> (in that order),
938 C<B> overloads C<+> with C<\&D::plus_sub>, and C<C> overloads
939 C<+> by C<"plus_meth">, then the subroutine C<D::plus_sub> will
940 be called to implement operation C<+> for an object in package C<A>.
944 Note that in Perl version prior to 5.18 inheritance of the C<fallback> key
945 was not governed by the above rules. The value of C<fallback> in the first
946 overloaded ancestor was used. This was fixed in 5.18 to follow the usual
947 rules of inheritance.
949 =head2 Run-time Overloading
951 Since all C<use> directives are executed at compile-time, the only way to
952 change overloading during run-time is to
954 eval 'use overload "+" => \&addmethod';
958 eval 'no overload "+", "--", "<="';
960 though the use of these constructs during run-time is questionable.
962 =head2 Public Functions
964 Package C<overload.pm> provides the following public functions:
968 =item overload::StrVal(arg)
970 Gives the string value of C<arg> as in the
971 absence of stringify overloading. If you
972 are using this to get the address of a reference (useful for checking if two
973 references point to the same thing) then you may be better off using
974 C<Scalar::Util::refaddr()>, which is faster.
976 =item overload::Overloaded(arg)
978 Returns true if C<arg> is subject to overloading of some operations.
980 =item overload::Method(obj,op)
982 Returns C<undef> or a reference to the method that implements C<op>.
986 =head2 Overloading Constants
988 For some applications, the Perl parser mangles constants too much.
989 It is possible to hook into this process via C<overload::constant()>
990 and C<overload::remove_constant()> functions.
992 These functions take a hash as an argument. The recognized keys of this hash
999 to overload integer constants,
1003 to overload floating point constants,
1007 to overload octal and hexadecimal constants,
1011 to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
1012 strings and here-documents,
1016 to overload constant pieces of regular expressions.
1020 The corresponding values are references to functions which take three arguments:
1021 the first one is the I<initial> string form of the constant, the second one
1022 is how Perl interprets this constant, the third one is how the constant is used.
1023 Note that the initial string form does not
1024 contain string delimiters, and has backslashes in backslash-delimiter
1025 combinations stripped (thus the value of delimiter is not relevant for
1026 processing of this string). The return value of this function is how this
1027 constant is going to be interpreted by Perl. The third argument is undefined
1028 unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
1029 context (comes from strings, regular expressions, and single-quote HERE
1030 documents), it is C<tr> for arguments of C<tr>/C<y> operators,
1031 it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
1033 Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
1034 it is expected that overloaded constant strings are equipped with reasonable
1035 overloaded catenation operator, otherwise absurd results will result.
1036 Similarly, negative numbers are considered as negations of positive constants.
1038 Note that it is probably meaningless to call the functions overload::constant()
1039 and overload::remove_constant() from anywhere but import() and unimport() methods.
1040 From these methods they may be called as
1045 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
1046 overload::constant integer => sub {Math::BigInt->new(shift)};
1049 =head1 IMPLEMENTATION
1051 What follows is subject to change RSN.
1053 The table of methods for all operations is cached in magic for the
1054 symbol table hash for the package. The cache is invalidated during
1055 processing of C<use overload>, C<no overload>, new function
1056 definitions, and changes in @ISA.
1058 (Every SVish thing has a magic queue, and magic is an entry in that
1059 queue. This is how a single variable may participate in multiple
1060 forms of magic simultaneously. For instance, environment variables
1061 regularly have two forms at once: their %ENV magic and their taint
1062 magic. However, the magic which implements overloading is applied to
1063 the stashes, which are rarely used directly, thus should not slow down
1066 If a package uses overload, it carries a special flag. This flag is also
1067 set when new functions are defined or @ISA is modified. There will be a
1068 slight speed penalty on the very first operation thereafter that supports
1069 overloading, while the overload tables are updated. If there is no
1070 overloading present, the flag is turned off. Thus the only speed penalty
1071 thereafter is the checking of this flag.
1073 It is expected that arguments to methods that are not explicitly supposed
1074 to be changed are constant (but this is not enforced).
1078 Please add examples to what follows!
1080 =head2 Two-face Scalars
1082 Put this in F<two_face.pm> in your Perl library directory:
1084 package two_face; # Scalars with separate string and
1086 sub new { my $p = shift; bless [@_], $p }
1087 use overload '""' => \&str, '0+' => \&num, fallback => 1;
1088 sub num {shift->[1]}
1089 sub str {shift->[0]}
1094 my $seven = two_face->new("vii", 7);
1095 printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
1096 print "seven contains 'i'\n" if $seven =~ /i/;
1098 (The second line creates a scalar which has both a string value, and a
1099 numeric value.) This prints:
1101 seven=vii, seven=7, eight=8
1104 =head2 Two-face References
1106 Suppose you want to create an object which is accessible as both an
1107 array reference and a hash reference.
1110 use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
1118 tie %h, ref $self, $self;
1122 sub TIEHASH { my $p = shift; bless \ shift, $p }
1125 $fields{$_} = $i++ foreach qw{zero one two three};
1127 my $self = ${shift()};
1128 my $key = $fields{shift()};
1129 defined $key or die "Out of band access";
1130 $$self->[$key] = shift;
1133 my $self = ${shift()};
1134 my $key = $fields{shift()};
1135 defined $key or die "Out of band access";
1139 Now one can access an object using both the array and hash syntax:
1141 my $bar = two_refs->new(3,4,5,6);
1143 $bar->{two} == 11 or die 'bad hash fetch';
1145 Note several important features of this example. First of all, the
1146 I<actual> type of $bar is a scalar reference, and we do not overload
1147 the scalar dereference. Thus we can get the I<actual> non-overloaded
1148 contents of $bar by just using C<$$bar> (what we do in functions which
1149 overload dereference). Similarly, the object returned by the
1150 TIEHASH() method is a scalar reference.
1152 Second, we create a new tied hash each time the hash syntax is used.
1153 This allows us not to worry about a possibility of a reference loop,
1154 which would lead to a memory leak.
1156 Both these problems can be cured. Say, if we want to overload hash
1157 dereference on a reference to an object which is I<implemented> as a
1158 hash itself, the only problem one has to circumvent is how to access
1159 this I<actual> hash (as opposed to the I<virtual> hash exhibited by the
1160 overloaded dereference operator). Here is one possible fetching routine:
1163 my ($self, $key) = (shift, shift);
1164 my $class = ref $self;
1165 bless $self, 'overload::dummy'; # Disable overloading of %{}
1166 my $out = $self->{$key};
1167 bless $self, $class; # Restore overloading
1171 To remove creation of the tied hash on each access, one may an extra
1172 level of indirection which allows a non-circular structure of references:
1175 use overload '%{}' => sub { ${shift()}->[1] },
1176 '@{}' => sub { ${shift()}->[0] };
1182 bless \ [$a, \%h], $p;
1187 tie %h, ref $self, $self;
1191 sub TIEHASH { my $p = shift; bless \ shift, $p }
1194 $fields{$_} = $i++ foreach qw{zero one two three};
1197 my $key = $fields{shift()};
1198 defined $key or die "Out of band access";
1203 my $key = $fields{shift()};
1204 defined $key or die "Out of band access";
1208 Now if $baz is overloaded like this, then C<$baz> is a reference to a
1209 reference to the intermediate array, which keeps a reference to an
1210 actual array, and the access hash. The tie()ing object for the access
1211 hash is a reference to a reference to the actual array, so
1217 There are no loops of references.
1221 Both "objects" which are blessed into the class C<two_refs1> are
1222 references to a reference to an array, thus references to a I<scalar>.
1223 Thus the accessor expression C<$$foo-E<gt>[$ind]> involves no
1224 overloaded operations.
1228 =head2 Symbolic Calculator
1230 Put this in F<symbolic.pm> in your Perl library directory:
1232 package symbolic; # Primitive symbolic calculator
1233 use overload nomethod => \&wrap;
1235 sub new { shift; bless ['n', @_] }
1237 my ($obj, $other, $inv, $meth) = @_;
1238 ($obj, $other) = ($other, $obj) if $inv;
1239 bless [$meth, $obj, $other];
1242 This module is very unusual as overloaded modules go: it does not
1243 provide any usual overloaded operators, instead it provides an
1244 implementation for L</C<nomethod>>. In this example the C<nomethod>
1245 subroutine returns an object which encapsulates operations done over
1246 the objects: C<< symbolic->new(3) >> contains C<['n', 3]>, C<< 2 +
1247 symbolic->new(3) >> contains C<['+', 2, ['n', 3]]>.
1249 Here is an example of the script which "calculates" the side of
1250 circumscribed octagon using the above package:
1253 my $iter = 1; # 2**($iter+2) = 8
1254 my $side = symbolic->new(1);
1258 $side = (sqrt(1 + $side**2) - 1)/$side;
1262 The value of $side is
1264 ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
1265 undef], 1], ['n', 1]]
1267 Note that while we obtained this value using a nice little script,
1268 there is no simple way to I<use> this value. In fact this value may
1269 be inspected in debugger (see L<perldebug>), but only if
1270 C<bareStringify> B<O>ption is set, and not via C<p> command.
1272 If one attempts to print this value, then the overloaded operator
1273 C<""> will be called, which will call C<nomethod> operator. The
1274 result of this operator will be stringified again, but this result is
1275 again of type C<symbolic>, which will lead to an infinite loop.
1277 Add a pretty-printer method to the module F<symbolic.pm>:
1280 my ($meth, $a, $b) = @{+shift};
1281 $a = 'u' unless defined $a;
1282 $b = 'u' unless defined $b;
1283 $a = $a->pretty if ref $a;
1284 $b = $b->pretty if ref $b;
1288 Now one can finish the script by
1290 print "side = ", $side->pretty, "\n";
1292 The method C<pretty> is doing object-to-string conversion, so it
1293 is natural to overload the operator C<""> using this method. However,
1294 inside such a method it is not necessary to pretty-print the
1295 I<components> $a and $b of an object. In the above subroutine
1296 C<"[$meth $a $b]"> is a catenation of some strings and components $a
1297 and $b. If these components use overloading, the catenation operator
1298 will look for an overloaded operator C<.>; if not present, it will
1299 look for an overloaded operator C<"">. Thus it is enough to use
1301 use overload nomethod => \&wrap, '""' => \&str;
1303 my ($meth, $a, $b) = @{+shift};
1304 $a = 'u' unless defined $a;
1305 $b = 'u' unless defined $b;
1309 Now one can change the last line of the script to
1311 print "side = $side\n";
1315 side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
1317 and one can inspect the value in debugger using all the possible
1320 Something is still amiss: consider the loop variable $cnt of the
1321 script. It was a number, not an object. We cannot make this value of
1322 type C<symbolic>, since then the loop will not terminate.
1324 Indeed, to terminate the cycle, the $cnt should become false.
1325 However, the operator C<bool> for checking falsity is overloaded (this
1326 time via overloaded C<"">), and returns a long string, thus any object
1327 of type C<symbolic> is true. To overcome this, we need a way to
1328 compare an object to 0. In fact, it is easier to write a numeric
1331 Here is the text of F<symbolic.pm> with such a routine added (and
1332 slightly modified str()):
1334 package symbolic; # Primitive symbolic calculator
1336 nomethod => \&wrap, '""' => \&str, '0+' => \#
1338 sub new { shift; bless ['n', @_] }
1340 my ($obj, $other, $inv, $meth) = @_;
1341 ($obj, $other) = ($other, $obj) if $inv;
1342 bless [$meth, $obj, $other];
1345 my ($meth, $a, $b) = @{+shift};
1346 $a = 'u' unless defined $a;
1353 my %subr = ( n => sub {$_[0]},
1354 sqrt => sub {sqrt $_[0]},
1355 '-' => sub {shift() - shift()},
1356 '+' => sub {shift() + shift()},
1357 '/' => sub {shift() / shift()},
1358 '*' => sub {shift() * shift()},
1359 '**' => sub {shift() ** shift()},
1362 my ($meth, $a, $b) = @{+shift};
1363 my $subr = $subr{$meth}
1364 or die "Do not know how to ($meth) in symbolic";
1365 $a = $a->num if ref $a eq __PACKAGE__;
1366 $b = $b->num if ref $b eq __PACKAGE__;
1370 All the work of numeric conversion is done in %subr and num(). Of
1371 course, %subr is not complete, it contains only operators used in the
1372 example below. Here is the extra-credit question: why do we need an
1373 explicit recursion in num()? (Answer is at the end of this section.)
1375 Use this module like this:
1378 my $iter = symbolic->new(2); # 16-gon
1379 my $side = symbolic->new(1);
1383 $cnt = $cnt - 1; # Mutator '--' not implemented
1384 $side = (sqrt(1 + $side**2) - 1)/$side;
1386 printf "%s=%f\n", $side, $side;
1387 printf "pi=%f\n", $side*(2**($iter+2));
1389 It prints (without so many line breaks)
1391 [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
1393 [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1396 The above module is very primitive. It does not implement
1397 mutator methods (C<++>, C<-=> and so on), does not do deep copying
1398 (not required without mutators!), and implements only those arithmetic
1399 operations which are used in the example.
1401 To implement most arithmetic operations is easy; one should just use
1402 the tables of operations, and change the code which fills %subr to
1404 my %subr = ( 'n' => sub {$_[0]} );
1405 foreach my $op (split " ", $overload::ops{with_assign}) {
1406 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1408 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1409 foreach my $op (split " ", "@overload::ops{ @bins }") {
1410 $subr{$op} = eval "sub {shift() $op shift()}";
1412 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1413 print "defining '$op'\n";
1414 $subr{$op} = eval "sub {$op shift()}";
1417 Since subroutines implementing assignment operators are not required
1418 to modify their operands (see L<Overloadable Operations> above),
1419 we do not need anything special to make C<+=> and friends work,
1420 besides adding these operators to %subr and defining a copy
1421 constructor (needed since Perl has no way to know that the
1422 implementation of C<'+='> does not mutate the argument -
1423 see L<Copy Constructor>).
1425 To implement a copy constructor, add C<< '=' => \&cpy >> to C<use overload>
1426 line, and code (this code assumes that mutators change things one level
1427 deep only, so recursive copying is not needed):
1431 bless [@$self], ref $self;
1434 To make C<++> and C<--> work, we need to implement actual mutators,
1435 either directly, or in C<nomethod>. We continue to do things inside
1436 C<nomethod>, thus add
1438 if ($meth eq '++' or $meth eq '--') {
1439 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1443 after the first line of wrap(). This is not a most effective
1444 implementation, one may consider
1446 sub inc { $_[0] = bless ['++', shift, 1]; }
1450 As a final remark, note that one can fill %subr by
1452 my %subr = ( 'n' => sub {$_[0]} );
1453 foreach my $op (split " ", $overload::ops{with_assign}) {
1454 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1456 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1457 foreach my $op (split " ", "@overload::ops{ @bins }") {
1458 $subr{$op} = eval "sub {shift() $op shift()}";
1460 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1461 $subr{$op} = eval "sub {$op shift()}";
1463 $subr{'++'} = $subr{'+'};
1464 $subr{'--'} = $subr{'-'};
1466 This finishes implementation of a primitive symbolic calculator in
1467 50 lines of Perl code. Since the numeric values of subexpressions
1468 are not cached, the calculator is very slow.
1470 Here is the answer for the exercise: In the case of str(), we need no
1471 explicit recursion since the overloaded C<.>-operator will fall back
1472 to an existing overloaded operator C<"">. Overloaded arithmetic
1473 operators I<do not> fall back to numeric conversion if C<fallback> is
1474 not explicitly requested. Thus without an explicit recursion num()
1475 would convert C<['+', $a, $b]> to C<$a + $b>, which would just rebuild
1476 the argument of num().
1478 If you wonder why defaults for conversion are different for str() and
1479 num(), note how easy it was to write the symbolic calculator. This
1480 simplicity is due to an appropriate choice of defaults. One extra
1481 note: due to the explicit recursion num() is more fragile than sym():
1482 we need to explicitly check for the type of $a and $b. If components
1483 $a and $b happen to be of some related type, this may lead to problems.
1485 =head2 I<Really> Symbolic Calculator
1487 One may wonder why we call the above calculator symbolic. The reason
1488 is that the actual calculation of the value of expression is postponed
1489 until the value is I<used>.
1491 To see it in action, add a method
1496 @$obj->[0,1] = ('=', shift);
1499 to the package C<symbolic>. After this change one can do
1501 my $a = symbolic->new(3);
1502 my $b = symbolic->new(4);
1503 my $c = sqrt($a**2 + $b**2);
1505 and the numeric value of $c becomes 5. However, after calling
1507 $a->STORE(12); $b->STORE(5);
1509 the numeric value of $c becomes 13. There is no doubt now that the module
1510 symbolic provides a I<symbolic> calculator indeed.
1512 To hide the rough edges under the hood, provide a tie()d interface to the
1513 package C<symbolic>. Add methods
1515 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
1517 sub nop { } # Around a bug
1519 (the bug, fixed in Perl 5.14, is described in L<"BUGS">). One can use this
1522 tie $a, 'symbolic', 3;
1523 tie $b, 'symbolic', 4;
1524 $a->nop; $b->nop; # Around a bug
1526 my $c = sqrt($a**2 + $b**2);
1528 Now numeric value of $c is 5. After C<$a = 12; $b = 5> the numeric value
1529 of $c becomes 13. To insulate the user of the module add a method
1531 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
1536 symbolic->vars($a, $b);
1537 my $c = sqrt($a**2 + $b**2);
1540 printf "c5 %s=%f\n", $c, $c;
1543 printf "c13 %s=%f\n", $c, $c;
1545 shows that the numeric value of $c follows changes to the values of $a
1550 Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
1554 The C<overloading> pragma can be used to enable or disable overloaded
1555 operations within a lexical scope - see L<overloading>.
1559 When Perl is run with the B<-Do> switch or its equivalent, overloading
1560 induces diagnostic messages.
1562 Using the C<m> command of Perl debugger (see L<perldebug>) one can
1563 deduce which operations are overloaded (and which ancestor triggers
1564 this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
1565 is shown by debugger. The method C<()> corresponds to the C<fallback>
1566 key (in fact a presence of this method shows that this package has
1567 overloading enabled, and it is what is used by the C<Overloaded>
1568 function of module C<overload>).
1570 The module might issue the following warnings:
1574 =item Odd number of arguments for overload::constant
1576 (W) The call to overload::constant contained an odd number of arguments.
1577 The arguments should come in pairs.
1579 =item '%s' is not an overloadable type
1581 (W) You tried to overload a constant type the overload package is unaware of.
1583 =item '%s' is not a code reference
1585 (W) The second (fourth, sixth, ...) argument of overload::constant needs
1586 to be a code reference. Either an anonymous subroutine, or a reference
1589 =item overload arg '%s' is invalid
1591 (W) C<use overload> was passed an argument it did not
1592 recognize. Did you mistype an operator?
1596 =head1 BUGS AND PITFALLS
1602 A pitfall when fallback is TRUE and Perl resorts to a built-in
1603 implementation of an operator is that some operators have more
1604 than one semantic, for example C<|>:
1606 use overload '0+' => sub { $_[0]->{n}; },
1608 my $x = bless { n => 4 }, "main";
1609 my $y = bless { n => 8 }, "main";
1610 print $x | $y, "\n";
1612 You might expect this to output "12".
1613 In fact, it prints "<": the ASCII result of treating "|"
1614 as a bitwise string operator - that is, the result of treating
1615 the operands as the strings "4" and "8" rather than numbers.
1616 The fact that numify (C<0+>) is implemented but stringify
1617 (C<"">) isn't makes no difference since the latter is simply
1618 autogenerated from the former.
1620 The only way to change this is to provide your own subroutine
1625 Magic autogeneration increases the potential for inadvertently
1626 creating self-referential structures.
1627 Currently Perl will not free self-referential
1628 structures until cycles are explicitly broken.
1631 use overload '+' => 'add';
1632 sub add { bless [ \$_[0], \$_[1] ] };
1634 is asking for trouble, since
1638 will effectively become
1640 $obj = add($obj, $y, undef);
1642 with the same result as
1644 $obj = [\$obj, \$foo];
1646 Even if no I<explicit> assignment-variants of operators are present in
1647 the script, they may be generated by the optimizer.
1654 my $tmp = 'obj = ' . $obj; $tmp .= "\n";
1658 The symbol table is filled with names looking like line-noise.
1662 This bug was fixed in Perl 5.18, but may still trip you up if you are using
1665 For the purpose of inheritance every overloaded package behaves as if
1666 C<fallback> is present (possibly undefined). This may create
1667 interesting effects if some package is not overloaded, but inherits
1668 from two overloaded packages.
1672 Before Perl 5.14, the relation between overloading and tie()ing was broken.
1673 Overloading was triggered or not based on the I<previous> class of the
1676 This happened because the presence of overloading was checked
1677 too early, before any tie()d access was attempted. If the
1678 class of the value FETCH()ed from the tied variable does not
1679 change, a simple workaround for code that is to run on older Perl
1680 versions is to access the value (via C<() = $foo> or some such)
1681 immediately after tie()ing, so that after this call the I<previous> class
1682 coincides with the current one.
1686 Barewords are not covered by overloaded string constants.
1690 The range operator C<..> cannot be overloaded.