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;
70 $package = ref $package if ref $package;
71 #my $meth = $package->can('(' . shift);
72 ov_method mycan($package, '(' . shift), $package;
73 #return $meth if $meth ne \&nil;
78 my $package = ref $_[0];
79 return "$_[0]" unless $package;
80 bless $_[0], overload::Fake; # Non-overloaded package
82 bless $_[0], $package; # Back
83 $package . substr $str, index $str, '=';
87 (OverloadedStringify($_[0])) ?
92 sub mycan { # Real can would leave stubs.
93 my ($package, $meth) = @_;
94 return \*{$package . "::$meth"} if defined &{$package . "::$meth"};
96 foreach $p (@{$package . "::ISA"}) {
97 my $out = mycan($p, $meth);
112 # Arguments: what, sub
115 $^H |= $constants{$_[0]} | 0x20000;
120 sub remove_constant {
121 # Arguments: what, sub
124 $^H &= ~ $constants{$_[0]};
135 overload - Package for overloading perl operations
148 $a = new SomeThing 57;
151 if (overload::Overloaded $b) {...}
153 $strval = overload::StrVal $b;
155 =head1 CAVEAT SCRIPTOR
157 Overloading of operators is a subject not to be taken lightly.
158 Neither its precise implementation, syntax, nor semantics are
159 100% endorsed by Larry Wall. So any of these may be changed
160 at some point in the future.
164 =head2 Declaration of overloaded functions
166 The compilation directive
173 declares function Number::add() for addition, and method muas() in
174 the "class" C<Number> (or one of its base classes)
175 for the assignment form C<*=> of multiplication.
177 Arguments of this directive come in (key, value) pairs. Legal values
178 are values legal inside a C<&{ ... }> call, so the name of a
179 subroutine, a reference to a subroutine, or an anonymous subroutine
180 will all work. Note that values specified as strings are
181 interpreted as methods, not subroutines. Legal keys are listed below.
183 The subroutine C<add> will be called to execute C<$a+$b> if $a
184 is a reference to an object blessed into the package C<Number>, or if $a is
185 not an object from a package with defined mathemagic addition, but $b is a
186 reference to a C<Number>. It can also be called in other situations, like
187 C<$a+=7>, or C<$a++>. See L<MAGIC AUTOGENERATION>. (Mathemagical
188 methods refer to methods triggered by an overloaded mathematical
191 Since overloading respects inheritance via the @ISA hierarchy, the
192 above declaration would also trigger overloading of C<+> and C<*=> in
193 all the packages which inherit from C<Number>.
195 =head2 Calling Conventions for Binary Operations
197 The functions specified in the C<use overload ...> directive are called
198 with three (in one particular case with four, see L<Last Resort>)
199 arguments. If the corresponding operation is binary, then the first
200 two arguments are the two arguments of the operation. However, due to
201 general object calling conventions, the first argument should always be
202 an object in the package, so in the situation of C<7+$a>, the
203 order of the arguments is interchanged. It probably does not matter
204 when implementing the addition method, but whether the arguments
205 are reversed is vital to the subtraction method. The method can
206 query this information by examining the third argument, which can take
207 three different values:
213 the order of arguments is as in the current operation.
217 the arguments are reversed.
221 the current operation is an assignment variant (as in
222 C<$a+=7>), but the usual function is called instead. This additional
223 information can be used to generate some optimizations.
227 =head2 Calling Conventions for Unary Operations
229 Unary operation are considered binary operations with the second
230 argument being C<undef>. Thus the functions that overloads C<{"++"}>
231 is called with arguments C<($a,undef,'')> when $a++ is executed.
233 =head2 Overloadable Operations
235 The following symbols can be specified in C<use overload>:
239 =item * I<Arithmetic operations>
241 "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
242 "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
244 For these operations a substituted non-assignment variant can be called if
245 the assignment variant is not available. Methods for operations "C<+>",
246 "C<->", "C<+=>", and "C<-=>" can be called to automatically generate
247 increment and decrement methods. The operation "C<->" can be used to
248 autogenerate missing methods for unary minus or C<abs>.
250 =item * I<Comparison operations>
252 "<", "<=", ">", ">=", "==", "!=", "<=>",
253 "lt", "le", "gt", "ge", "eq", "ne", "cmp",
255 If the corresponding "spaceship" variant is available, it can be
256 used to substitute for the missing operation. During C<sort>ing
257 arrays, C<cmp> is used to compare values subject to C<use overload>.
259 =item * I<Bit operations>
261 "&", "^", "|", "neg", "!", "~",
263 "C<neg>" stands for unary minus. If the method for C<neg> is not
264 specified, it can be autogenerated using the method for
265 subtraction. If the method for "C<!>" is not specified, it can be
266 autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
268 =item * I<Increment and decrement>
272 If undefined, addition and subtraction methods can be
273 used instead. These operations are called both in prefix and
276 =item * I<Transcendental functions>
278 "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
280 If C<abs> is unavailable, it can be autogenerated using methods
281 for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
283 =item * I<Boolean, string and numeric conversion>
285 "bool", "\"\"", "0+",
287 If one or two of these operations are unavailable, the remaining ones can
288 be used instead. C<bool> is used in the flow control operators
289 (like C<while>) and for the ternary "C<?:>" operation. These functions can
290 return any arbitrary Perl value. If the corresponding operation for this value
291 is overloaded too, that operation will be called again with this value.
295 "nomethod", "fallback", "=",
297 see L<SPECIAL SYMBOLS FOR C<use overload>>.
301 See L<"Fallback"> for an explanation of when a missing method can be autogenerated.
303 =head2 Inheritance and overloading
305 Inheritance interacts with overloading in two ways.
309 =item Strings as values of C<use overload> directive
313 use overload key => value;
315 is a string, it is interpreted as a method name.
317 =item Overloading of an operation is inherited by derived classes
319 Any class derived from an overloaded class is also overloaded. The
320 set of overloaded methods is the union of overloaded methods of all
321 the ancestors. If some method is overloaded in several ancestor, then
322 which description will be used is decided by the usual inheritance
325 If C<A> inherits from C<B> and C<C> (in this order), C<B> overloads
326 C<+> with C<\&D::plus_sub>, and C<C> overloads C<+> by C<"plus_meth">,
327 then the subroutine C<D::plus_sub> will be called to implement
328 operation C<+> for an object in package C<A>.
332 Note that since the value of the C<fallback> key is not a subroutine,
333 its inheritance is not governed by the above rules. In the current
334 implementation, the value of C<fallback> in the first overloaded
335 ancestor is used, but this is accidental and subject to change.
337 =head1 SPECIAL SYMBOLS FOR C<use overload>
339 Three keys are recognized by Perl that are not covered by the above
344 C<"nomethod"> should be followed by a reference to a function of four
345 parameters. If defined, it is called when the overloading mechanism
346 cannot find a method for some operation. The first three arguments of
347 this function coincide with the arguments for the corresponding method if
348 it were found, the fourth argument is the symbol
349 corresponding to the missing method. If several methods are tried,
350 the last one is used. Say, C<1-$a> can be equivalent to
352 &nomethodMethod($a,1,1,"-")
354 if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
355 C<use overload> directive.
357 If some operation cannot be resolved, and there is no function
358 assigned to C<"nomethod">, then an exception will be raised via die()--
359 unless C<"fallback"> was specified as a key in C<use overload> directive.
363 The key C<"fallback"> governs what to do if a method for a particular
364 operation is not found. Three different cases are possible depending on
365 the value of C<"fallback">:
372 substituted method (see L<MAGIC AUTOGENERATION>). If this fails, it
373 then tries to calls C<"nomethod"> value; if missing, an exception
378 The same as for the C<undef> value, but no exception is raised. Instead,
379 it silently reverts to what it would have done were there no C<use overload>
382 =item * defined, but FALSE
384 No autogeneration is tried. Perl tries to call
385 C<"nomethod"> value, and if this is missing, raises an exception.
389 B<Note.> C<"fallback"> inheritance via @ISA is not carved in stone
390 yet, see L<"Inheritance and overloading">.
392 =head2 Copy Constructor
394 The value for C<"="> is a reference to a function with three
395 arguments, i.e., it looks like the other values in C<use
396 overload>. However, it does not overload the Perl assignment
397 operator. This would go against Camel hair.
399 This operation is called in the situations when a mutator is applied
400 to a reference that shares its object with some other reference, such
406 To make this change $a and not change $b, a copy of C<$$a> is made,
407 and $a is assigned a reference to this new object. This operation is
408 done during execution of the C<$a++>, and not during the assignment,
409 (so before the increment C<$$a> coincides with C<$$b>). This is only
410 done if C<++> is expressed via a method for C<'++'> or C<'+='>. Note
411 that if this operation is expressed via C<'+'> a nonmutator, i.e., as
417 then C<$a> does not reference a new copy of C<$$a>, since $$a does not
418 appear as lvalue when the above code is executed.
420 If the copy constructor is required during the execution of some mutator,
421 but a method for C<'='> was not specified, it can be autogenerated as a
422 string copy if the object is a plain scalar.
428 The actually executed code for
431 Something else which does not modify $a or $b....
437 Something else which does not modify $a or $b....
438 $a = $a->clone(undef,"");
441 if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
442 C<'='> was overloaded with C<\&clone>.
446 =head1 MAGIC AUTOGENERATION
448 If a method for an operation is not found, and the value for C<"fallback"> is
449 TRUE or undefined, Perl tries to autogenerate a substitute method for
450 the missing operation based on the defined operations. Autogenerated method
451 substitutions are possible for the following operations:
455 =item I<Assignment forms of arithmetic operations>
457 C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
460 =item I<Conversion operations>
462 String, numeric, and boolean conversion are calculated in terms of one
463 another if not all of them are defined.
465 =item I<Increment and decrement>
467 The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
468 and C<$a--> in terms of C<$a-=1> and C<$a-1>.
472 can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
476 can be expressed in terms of subtraction.
480 C<!> and C<not> can be expressed in terms of boolean conversion, or
481 string or numerical conversion.
483 =item I<Concatenation>
485 can be expressed in terms of string conversion.
487 =item I<Comparison operations>
489 can be expressed in terms of its "spaceship" counterpart: either
490 C<E<lt>=E<gt>> or C<cmp>:
492 <, >, <=, >=, ==, != in terms of <=>
493 lt, gt, le, ge, eq, ne in terms of cmp
495 =item I<Copy operator>
497 can be expressed in terms of an assignment to the dereferenced value, if this
498 value is a scalar and not a reference.
504 The restriction for the comparison operation is that even if, for example,
505 `C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
506 function will produce only a standard logical value based on the
507 numerical value of the result of `C<cmp>'. In particular, a working
508 numeric conversion is needed in this case (possibly expressed in terms of
511 Similarly, C<.=> and C<x=> operators lose their mathemagical properties
512 if the string conversion substitution is applied.
514 When you chop() a mathemagical object it is promoted to a string and its
515 mathemagical properties are lost. The same can happen with other
518 =head1 Run-time Overloading
520 Since all C<use> directives are executed at compile-time, the only way to
521 change overloading during run-time is to
523 eval 'use overload "+" => \&addmethod';
527 eval 'no overload "+", "--", "<="';
529 though the use of these constructs during run-time is questionable.
531 =head1 Public functions
533 Package C<overload.pm> provides the following public functions:
537 =item overload::StrVal(arg)
539 Gives string value of C<arg> as in absence of stringify overloading.
541 =item overload::Overloaded(arg)
543 Returns true if C<arg> is subject to overloading of some operations.
545 =item overload::Method(obj,op)
547 Returns C<undef> or a reference to the method that implements C<op>.
551 =head1 Overloading constants
553 For some application Perl parser mangles constants too much. It is possible
554 to hook into this process via overload::constant() and overload::remove_constant()
557 These functions take a hash as an argument. The recognized keys of this hash
564 to overload integer constants,
568 to overload floating point constants,
572 to overload octal and hexadecimal constants,
576 to overload C<q>-quoted strings, constant pieces of C<qq>- and C<qx>-quoted
577 strings and here-documents,
581 to overload constant pieces of regular expressions.
585 The corresponding values are references to functions which take three arguments:
586 the first one is the I<initial> string form of the constant, the second one
587 is how Perl interprets this constant, the third one is how the constant is used.
588 Note that the initial string form does not
589 contain string delimiters, and has backslashes in backslash-delimiter
590 combinations stripped (thus the value of delimiter is not relevant for
591 processing of this string). The return value of this function is how this
592 constant is going to be interpreted by Perl. The third argument is undefined
593 unless for overloaded C<q>- and C<qr>- constants, it is C<q> in single-quote
594 context (comes from strings, regular expressions, and single-quote HERE
595 documents), it is C<tr> for arguments of C<tr>/C<y> operators,
596 it is C<s> for right-hand side of C<s>-operator, and it is C<qq> otherwise.
598 Since an expression C<"ab$cd,,"> is just a shortcut for C<'ab' . $cd . ',,'>,
599 it is expected that overloaded constant strings are equipped with reasonable
600 overloaded catenation operator, otherwise absurd results will result.
601 Similarly, negative numbers are considered as negations of positive constants.
603 Note that it is probably meaningless to call the functions overload::constant()
604 and overload::remove_constant() from anywhere but import() and unimport() methods.
605 From these methods they may be called as
610 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
611 overload::constant integer => sub {Math::BigInt->new(shift)};
614 B<BUGS> Currently overloaded-ness of constants does not propagate
617 =head1 IMPLEMENTATION
619 What follows is subject to change RSN.
621 The table of methods for all operations is cached in magic for the
622 symbol table hash for the package. The cache is invalidated during
623 processing of C<use overload>, C<no overload>, new function
624 definitions, and changes in @ISA. However, this invalidation remains
625 unprocessed until the next C<bless>ing into the package. Hence if you
626 want to change overloading structure dynamically, you'll need an
627 additional (fake) C<bless>ing to update the table.
629 (Every SVish thing has a magic queue, and magic is an entry in that
630 queue. This is how a single variable may participate in multiple
631 forms of magic simultaneously. For instance, environment variables
632 regularly have two forms at once: their %ENV magic and their taint
633 magic. However, the magic which implements overloading is applied to
634 the stashes, which are rarely used directly, thus should not slow down
637 If an object belongs to a package using overload, it carries a special
638 flag. Thus the only speed penalty during arithmetic operations without
639 overloading is the checking of this flag.
641 In fact, if C<use overload> is not present, there is almost no overhead
642 for overloadable operations, so most programs should not suffer
643 measurable performance penalties. A considerable effort was made to
644 minimize the overhead when overload is used in some package, but the
645 arguments in question do not belong to packages using overload. When
646 in doubt, test your speed with C<use overload> and without it. So far
647 there have been no reports of substantial speed degradation if Perl is
648 compiled with optimization turned on.
650 There is no size penalty for data if overload is not used. The only
651 size penalty if overload is used in some package is that I<all> the
652 packages acquire a magic during the next C<bless>ing into the
653 package. This magic is three-words-long for packages without
654 overloading, and carries the cache tabel if the package is overloaded.
656 Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
657 carried out before any operation that can imply an assignment to the
658 object $a (or $b) refers to, like C<$a++>. You can override this
659 behavior by defining your own copy constructor (see L<"Copy Constructor">).
661 It is expected that arguments to methods that are not explicitly supposed
662 to be changed are constant (but this is not enforced).
666 Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
670 When Perl is run with the B<-Do> switch or its equivalent, overloading
671 induces diagnostic messages.
673 Using the C<m> command of Perl debugger (see L<perldebug>) one can
674 deduce which operations are overloaded (and which ancestor triggers
675 this overloading). Say, if C<eq> is overloaded, then the method C<(eq>
676 is shown by debugger. The method C<()> corresponds to the C<fallback>
677 key (in fact a presence of this method shows that this package has
678 overloading enabled, and it is what is used by the C<Overloaded>
683 Because it is used for overloading, the per-package hash %OVERLOAD now
684 has a special meaning in Perl. The symbol table is filled with names
685 looking like line-noise.
687 For the purpose of inheritance every overloaded package behaves as if
688 C<fallback> is present (possibly undefined). This may create
689 interesting effects if some package is not overloaded, but inherits
690 from two overloaded packages.
692 Barewords are not covered by overloaded string constants.
694 This document is confusing.