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 $sub = "${'package'}::$sub";
19 #print STDERR "Setting `$ {'package'}::\cO$_' to \\&`$sub'.\n";
20 *{$package . "::(" . $_} = \&{ $sub };
23 ${$package . "::()"} = $fb; # Make it findable too (fallback only).
27 $package = (caller())[0];
28 # *{$package . "::OVERLOAD"} = \&OVERLOAD;
30 $package->overload::OVERLOAD(@_);
34 $package = (caller())[0];
35 ${$package . "::OVERLOAD"}{dummy}++; # Upgrade the table
38 if ($_ eq 'fallback') {
39 undef $ {$package . "::()"};
41 delete $ {$package . "::"}{"(" . $_};
48 $package = ref $package if ref $package;
52 sub OverloadedStringify {
54 $package = ref $package if ref $package;
60 $package = ref $package if ref $package;
61 $package->can('(' . shift)
65 my $package = ref $_[0];
66 return "$_[0]" unless $package;
67 bless $_[0], overload::Fake; # Non-overloaded package
69 bless $_[0], $package; # Back
70 $package . substr $str, index $str, '=';
74 (OverloadedStringify($_[0])) ?
85 overload - Package for overloading perl operations
98 $a = new SomeThing 57;
101 if (overload::Overloaded $b) {...}
103 $strval = overload::StrVal $b;
105 =head1 CAVEAT SCRIPTOR
107 Overloading of operators is a subject not to be taken lightly.
108 Neither its precise implementation, syntax, nor semantics are
109 100% endorsed by Larry Wall. So any of these may be changed
110 at some point in the future.
114 =head2 Declaration of overloaded functions
116 The compilation directive
123 declares function Number::add() for addition, and method muas() in
124 the "class" C<Number> (or one of its base classes)
125 for the assignment form C<*=> of multiplication.
127 Arguments of this directive come in (key, value) pairs. Legal values
128 are values legal inside a C<&{ ... }> call, so the name of a subroutine,
129 a reference to a subroutine, or an anonymous subroutine will all work.
130 Legal keys are listed below.
132 The subroutine C<add> will be called to execute C<$a+$b> if $a
133 is a reference to an object blessed into the package C<Number>, or if $a is
134 not an object from a package with defined mathemagic addition, but $b is a
135 reference to a C<Number>. It can also be called in other situations, like
136 C<$a+=7>, or C<$a++>. See L<MAGIC AUTOGENERATION>. (Mathemagical
137 methods refer to methods triggered by an overloaded mathematical
140 =head2 Calling Conventions for Binary Operations
142 The functions specified in the C<use overload ...> directive are called
143 with three (in one particular case with four, see L<Last Resort>)
144 arguments. If the corresponding operation is binary, then the first
145 two arguments are the two arguments of the operation. However, due to
146 general object calling conventions, the first argument should always be
147 an object in the package, so in the situation of C<7+$a>, the
148 order of the arguments is interchanged. It probably does not matter
149 when implementing the addition method, but whether the arguments
150 are reversed is vital to the subtraction method. The method can
151 query this information by examining the third argument, which can take
152 three different values:
158 the order of arguments is as in the current operation.
162 the arguments are reversed.
166 the current operation is an assignment variant (as in
167 C<$a+=7>), but the usual function is called instead. This additional
168 information can be used to generate some optimizations.
172 =head2 Calling Conventions for Unary Operations
174 Unary operation are considered binary operations with the second
175 argument being C<undef>. Thus the functions that overloads C<{"++"}>
176 is called with arguments C<($a,undef,'')> when $a++ is executed.
178 =head2 Overloadable Operations
180 The following symbols can be specified in C<use overload>:
184 =item * I<Arithmetic operations>
186 "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
187 "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
189 For these operations a substituted non-assignment variant can be called if
190 the assignment variant is not available. Methods for operations "C<+>",
191 "C<->", "C<+=>", and "C<-=>" can be called to automatically generate
192 increment and decrement methods. The operation "C<->" can be used to
193 autogenerate missing methods for unary minus or C<abs>.
195 =item * I<Comparison operations>
197 "<", "<=", ">", ">=", "==", "!=", "<=>",
198 "lt", "le", "gt", "ge", "eq", "ne", "cmp",
200 If the corresponding "spaceship" variant is available, it can be
201 used to substitute for the missing operation. During C<sort>ing
202 arrays, C<cmp> is used to compare values subject to C<use overload>.
204 =item * I<Bit operations>
206 "&", "^", "|", "neg", "!", "~",
208 "C<neg>" stands for unary minus. If the method for C<neg> is not
209 specified, it can be autogenerated using the method for
210 subtraction. If the method for "C<!>" is not specified, it can be
211 autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
213 =item * I<Increment and decrement>
217 If undefined, addition and subtraction methods can be
218 used instead. These operations are called both in prefix and
221 =item * I<Transcendental functions>
223 "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
225 If C<abs> is unavailable, it can be autogenerated using methods
226 for "E<lt>" or "E<lt>=E<gt>" combined with either unary minus or subtraction.
228 =item * I<Boolean, string and numeric conversion>
230 "bool", "\"\"", "0+",
232 If one or two of these operations are unavailable, the remaining ones can
233 be used instead. C<bool> is used in the flow control operators
234 (like C<while>) and for the ternary "C<?:>" operation. These functions can
235 return any arbitrary Perl value. If the corresponding operation for this value
236 is overloaded too, that operation will be called again with this value.
240 "nomethod", "fallback", "=",
242 see L<SPECIAL SYMBOLS FOR C<use overload>>.
246 See L<"Fallback"> for an explanation of when a missing method can be autogenerated.
248 =head1 SPECIAL SYMBOLS FOR C<use overload>
250 Three keys are recognized by Perl that are not covered by the above
255 C<"nomethod"> should be followed by a reference to a function of four
256 parameters. If defined, it is called when the overloading mechanism
257 cannot find a method for some operation. The first three arguments of
258 this function coincide with the arguments for the corresponding method if
259 it were found, the fourth argument is the symbol
260 corresponding to the missing method. If several methods are tried,
261 the last one is used. Say, C<1-$a> can be equivalent to
263 &nomethodMethod($a,1,1,"-")
265 if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
266 C<use overload> directive.
268 If some operation cannot be resolved, and there is no function
269 assigned to C<"nomethod">, then an exception will be raised via die()--
270 unless C<"fallback"> was specified as a key in C<use overload> directive.
274 The key C<"fallback"> governs what to do if a method for a particular
275 operation is not found. Three different cases are possible depending on
276 the value of C<"fallback">:
283 substituted method (see L<MAGIC AUTOGENERATION>). If this fails, it
284 then tries to calls C<"nomethod"> value; if missing, an exception
289 The same as for the C<undef> value, but no exception is raised. Instead,
290 it silently reverts to what it would have done were there no C<use overload>
293 =item * defined, but FALSE
295 No autogeneration is tried. Perl tries to call
296 C<"nomethod"> value, and if this is missing, raises an exception.
300 =head2 Copy Constructor
302 The value for C<"="> is a reference to a function with three
303 arguments, i.e., it looks like the other values in C<use
304 overload>. However, it does not overload the Perl assignment
305 operator. This would go against Camel hair.
307 This operation is called in the situations when a mutator is applied
308 to a reference that shares its object with some other reference, such
314 To make this change $a and not change $b, a copy of C<$$a> is made,
315 and $a is assigned a reference to this new object. This operation is
316 done during execution of the C<$a++>, and not during the assignment,
317 (so before the increment C<$$a> coincides with C<$$b>). This is only
318 done if C<++> is expressed via a method for C<'++'> or C<'+='>. Note
319 that if this operation is expressed via C<'+'> a nonmutator, i.e., as
325 then C<$a> does not reference a new copy of C<$$a>, since $$a does not
326 appear as lvalue when the above code is executed.
328 If the copy constructor is required during the execution of some mutator,
329 but a method for C<'='> was not specified, it can be autogenerated as a
330 string copy if the object is a plain scalar.
336 The actually executed code for
339 Something else which does not modify $a or $b....
345 Something else which does not modify $a or $b....
346 $a = $a->clone(undef,"");
349 if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
350 C<'='> was overloaded with C<\&clone>.
354 =head1 MAGIC AUTOGENERATION
356 If a method for an operation is not found, and the value for C<"fallback"> is
357 TRUE or undefined, Perl tries to autogenerate a substitute method for
358 the missing operation based on the defined operations. Autogenerated method
359 substitutions are possible for the following operations:
363 =item I<Assignment forms of arithmetic operations>
365 C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
368 =item I<Conversion operations>
370 String, numeric, and boolean conversion are calculated in terms of one
371 another if not all of them are defined.
373 =item I<Increment and decrement>
375 The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
376 and C<$a--> in terms of C<$a-=1> and C<$a-1>.
380 can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
384 can be expressed in terms of subtraction.
388 C<!> and C<not> can be expressed in terms of boolean conversion, or
389 string or numerical conversion.
391 =item I<Concatenation>
393 can be expressed in terms of string conversion.
395 =item I<Comparison operations>
397 can be expressed in terms of its "spaceship" counterpart: either
398 C<E<lt>=E<gt>> or C<cmp>:
400 <, >, <=, >=, ==, != in terms of <=>
401 lt, gt, le, ge, eq, ne in terms of cmp
403 =item I<Copy operator>
405 can be expressed in terms of an assignment to the dereferenced value, if this
406 value is a scalar and not a reference.
412 The restriction for the comparison operation is that even if, for example,
413 `C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
414 function will produce only a standard logical value based on the
415 numerical value of the result of `C<cmp>'. In particular, a working
416 numeric conversion is needed in this case (possibly expressed in terms of
419 Similarly, C<.=> and C<x=> operators lose their mathemagical properties
420 if the string conversion substitution is applied.
422 When you chop() a mathemagical object it is promoted to a string and its
423 mathemagical properties are lost. The same can happen with other
426 =head1 Run-time Overloading
428 Since all C<use> directives are executed at compile-time, the only way to
429 change overloading during run-time is to
431 eval 'use overload "+" => \&addmethod';
435 eval 'no overload "+", "--", "<="';
437 though the use of these constructs during run-time is questionable.
439 =head1 Public functions
441 Package C<overload.pm> provides the following public functions:
445 =item overload::StrVal(arg)
447 Gives string value of C<arg> as in absence of stringify overloading.
449 =item overload::Overloaded(arg)
451 Returns true if C<arg> is subject to overloading of some operations.
453 =item overload::Method(obj,op)
455 Returns C<undef> or a reference to the method that implements C<op>.
459 =head1 IMPLEMENTATION
461 What follows is subject to change RSN.
463 The table of methods for all operations is cached as magic in the
464 symbol table hash for the package. The table is rechecked for changes due to
465 C<use overload>, C<no overload>, and @ISA only during
466 C<bless>ing; so if they are changed dynamically, you'll need an
467 additional fake C<bless>ing to update the table.
469 (Every SVish thing has a magic queue, and magic is an entry in that queue.
470 This is how a single variable may participate in multiple forms of magic
471 simultaneously. For instance, environment variables regularly have two
472 forms at once: their %ENV magic and their taint magic.)
474 If an object belongs to a package using overload, it carries a special
475 flag. Thus the only speed penalty during arithmetic operations without
476 overloading is the checking of this flag.
478 In fact, if C<use overload> is not present, there is almost no overhead for
479 overloadable operations, so most programs should not suffer measurable
480 performance penalties. A considerable effort was made to minimize the overhead
481 when overload is used and the current operation is overloadable but
482 the arguments in question do not belong to packages using overload. When
483 in doubt, test your speed with C<use overload> and without it. So far there
484 have been no reports of substantial speed degradation if Perl is compiled
485 with optimization turned on.
487 There is no size penalty for data if overload is not used.
489 Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
490 carried out before any operation that can imply an assignment to the
491 object $a (or $b) refers to, like C<$a++>. You can override this
492 behavior by defining your own copy constructor (see L<"Copy Constructor">).
494 It is expected that arguments to methods that are not explicitly supposed
495 to be changed are constant (but this is not enforced).
499 Ilya Zakharevich E<lt>F<ilya@math.mps.ohio-state.edu>E<gt>.
503 When Perl is run with the B<-Do> switch or its equivalent, overloading
504 induces diagnostic messages.
508 Because it is used for overloading, the per-package associative array
509 %OVERLOAD now has a special meaning in Perl. The symbol table is
510 filled with names looking like line-noise.
512 For the purpose of inheritance every overloaded package behaves as if
513 C<fallback> is present (possibly undefined). This may create
514 interesting effects if some package is not overloaded, but inherits
515 from two overloaded packages.
517 This document is confusing.