6 my $hash = \%{$package . "::OVERLOAD"};
8 $hash->{$_} = $arg{$_};
13 $package = (caller())[0];
14 # *{$package . "::OVERLOAD"} = \&OVERLOAD;
16 $package->overload::OVERLOAD(@_);
20 $package = (caller())[0];
21 my $hash = \%{$package . "::OVERLOAD"};
29 ($package = ref $_[0]) and defined %{$package . "::OVERLOAD"};
32 sub OverloadedStringify {
33 ($package = ref $_[0]) and
34 defined %{$package . "::OVERLOAD"} and
35 exists $ {$package . "::OVERLOAD"}{'""'} and
36 defined &{$ {$package . "::OVERLOAD"}{'""'}};
40 ($package = ref $_[0]) and
41 defined %{$package . "::OVERLOAD"} and
42 $ {$package . "::OVERLOAD"}{$_[1]};
47 bless $_[0], Overload::Fake; # Non-overloaded package
49 bless $_[0], $package; # Back
54 (OverloadedStringify) ?
65 overload - Package for overloading perl operations
78 $a = new SomeThing 57;
81 if (overload::Overloaded $b) {...}
83 $strval = overload::StrVal $b;
85 =head1 CAVEAT SCRIPTOR
87 Overloading of operators is a subject not to be taken lightly.
88 Neither its precise implementation, syntax, nor semantics are
89 100% endorsed by Larry Wall. So any of these may be changed
90 at some point in the future.
94 =head2 Declaration of overloaded functions
96 The compilation directive
103 declares function Number::add() for addition, and method muas() in
104 the "class" C<Number> (or one of its base classes)
105 for the assignment form C<*=> of multiplication.
107 Arguments of this directive come in (key, value) pairs. Legal values
108 are values legal inside a C<&{ ... }> call, so the name of a subroutine,
109 a reference to a subroutine, or an anonymous subroutine will all work.
110 Legal keys are listed below.
112 The subroutine C<add> will be called to execute C<$a+$b> if $a
113 is a reference to an object blessed into the package C<Number>, or if $a is
114 not an object from a package with defined mathemagic addition, but $b is a
115 reference to a C<Number>. It can also be called in other situations, like
116 C<$a+=7>, or C<$a++>. See L<MAGIC AUTOGENERATION>. (Mathemagical
117 methods refer to methods triggered by an overloaded mathematical
120 =head2 Calling Conventions for Binary Operations
122 The functions specified in the C<use overload ...> directive are called
123 with three (in one particular case with four, see L<Last Resort>)
124 arguments. If the corresponding operation is binary, then the first
125 two arguments are the two arguments of the operation. However, due to
126 general object calling conventions, the first argument should always be
127 an object in the package, so in the situation of C<7+$a>, the
128 order of the arguments is interchanged. It probably does not matter
129 when implementing the addition method, but whether the arguments
130 are reversed is vital to the subtraction method. The method can
131 query this information by examining the third argument, which can take
132 three different values:
138 the order of arguments is as in the current operation.
142 the arguments are reversed.
146 the current operation is an assignment variant (as in
147 C<$a+=7>), but the usual function is called instead. This additional
148 information can be used to generate some optimizations.
152 =head2 Calling Conventions for Unary Operations
154 Unary operation are considered binary operations with the second
155 argument being C<undef>. Thus the functions that overloads C<{"++"}>
156 is called with arguments C<($a,undef,'')> when $a++ is executed.
158 =head2 Overloadable Operations
160 The following symbols can be specified in C<use overload>:
164 =item * I<Arithmetic operations>
166 "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
167 "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
169 For these operations a substituted non-assignment variant can be called if
170 the assignment variant is not available. Methods for operations "C<+>",
171 "C<->", "C<+=>", and "C<-=>" can be called to automatically generate
172 increment and decrement methods. The operation "C<->" can be used to
173 autogenerate missing methods for unary minus or C<abs>.
175 =item * I<Comparison operations>
177 "<", "<=", ">", ">=", "==", "!=", "<=>",
178 "lt", "le", "gt", "ge", "eq", "ne", "cmp",
180 If the corresponding "spaceship" variant is available, it can be
181 used to substitute for the missing operation. During C<sort>ing
182 arrays, C<cmp> is used to compare values subject to C<use overload>.
184 =item * I<Bit operations>
186 "&", "^", "|", "neg", "!", "~",
188 "C<neg>" stands for unary minus. If the method for C<neg> is not
189 specified, it can be autogenerated using the method for
190 subtraction. If the method for "C<!>" is not specified, it can be
191 autogenerated using the methods for "C<bool>", or "C<\"\">", or "C<0+>".
193 =item * I<Increment and decrement>
197 If undefined, addition and subtraction methods can be
198 used instead. These operations are called both in prefix and
201 =item * I<Transcendental functions>
203 "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
205 If C<abs> is unavailable, it can be autogenerated using methods
206 for "<" or "<=>" combined with either unary minus or subtraction.
208 =item * I<Boolean, string and numeric conversion>
210 "bool", "\"\"", "0+",
212 If one or two of these operations are unavailable, the remaining ones can
213 be used instead. C<bool> is used in the flow control operators
214 (like C<while>) and for the ternary "C<?:>" operation. These functions can
215 return any arbitrary Perl value. If the corresponding operation for this value
216 is overloaded too, that operation will be called again with this value.
220 "nomethod", "fallback", "=",
222 see L<SPECIAL SYMBOLS FOR C<use overload>>.
226 See L<"Fallback"> for an explanation of when a missing method can be autogenerated.
228 =head1 SPECIAL SYMBOLS FOR C<use overload>
230 Three keys are recognized by Perl that are not covered by the above
235 C<"nomethod"> should be followed by a reference to a function of four
236 parameters. If defined, it is called when the overloading mechanism
237 cannot find a method for some operation. The first three arguments of
238 this function coincide with the arguments for the corresponding method if
239 it were found, the fourth argument is the symbol
240 corresponding to the missing method. If several methods are tried,
241 the last one is used. Say, C<1-$a> can be equivalent to
243 &nomethodMethod($a,1,1,"-")
245 if the pair C<"nomethod" =E<gt> "nomethodMethod"> was specified in the
246 C<use overload> directive.
248 If some operation cannot be resolved, and there is no function
249 assigned to C<"nomethod">, then an exception will be raised via die()--
250 unless C<"fallback"> was specified as a key in C<use overload> directive.
254 The key C<"fallback"> governs what to do if a method for a particular
255 operation is not found. Three different cases are possible depending on
256 the value of C<"fallback">:
263 substituted method (see L<MAGIC AUTOGENERATION>). If this fails, it
264 then tries to calls C<"nomethod"> value; if missing, an exception
269 The same as for the C<undef> value, but no exception is raised. Instead,
270 it silently reverts to what it would have done were there no C<use overload>
273 =item * defined, but FALSE
275 No autogeneration is tried. Perl tries to call
276 C<"nomethod"> value, and if this is missing, raises an exception.
280 =head2 Copy Constructor
282 The value for C<"="> is a reference to a function with three
283 arguments, i.e., it looks like the other values in C<use
284 overload>. However, it does not overload the Perl assignment
285 operator. This would go against Camel hair.
287 This operation is called in the situations when a mutator is applied
288 to a reference that shares its object with some other reference, such
294 To make this change $a and not change $b, a copy of C<$$a> is made,
295 and $a is assigned a reference to this new object. This operation is
296 done during execution of the C<$a++>, and not during the assignment,
297 (so before the increment C<$$a> coincides with C<$$b>). This is only
298 done if C<++> is expressed via a method for C<'++'> or C<'+='>. Note
299 that if this operation is expressed via C<'+'> a nonmutator, i.e., as
305 then C<$a> does not reference a new copy of C<$$a>, since $$a does not
306 appear as lvalue when the above code is executed.
308 If the copy constructor is required during the execution of some mutator,
309 but a method for C<'='> was not specified, it can be autogenerated as a
310 string copy if the object is a plain scalar.
316 The actually executed code for
319 Something else which does not modify $a or $b....
325 Something else which does not modify $a or $b....
326 $a = $a->clone(undef,"");
329 if $b was mathemagical, and C<'++'> was overloaded with C<\&incr>,
330 C<'='> was overloaded with C<\&clone>.
334 =head1 MAGIC AUTOGENERATION
336 If a method for an operation is not found, and the value for C<"fallback"> is
337 TRUE or undefined, Perl tries to autogenerate a substitute method for
338 the missing operation based on the defined operations. Autogenerated method
339 substitutions are possible for the following operations:
343 =item I<Assignment forms of arithmetic operations>
345 C<$a+=$b> can use the method for C<"+"> if the method for C<"+=">
348 =item I<Conversion operations>
350 String, numeric, and boolean conversion are calculated in terms of one
351 another if not all of them are defined.
353 =item I<Increment and decrement>
355 The C<++$a> operation can be expressed in terms of C<$a+=1> or C<$a+1>,
356 and C<$a--> in terms of C<$a-=1> and C<$a-1>.
360 can be expressed in terms of C<$aE<lt>0> and C<-$a> (or C<0-$a>).
364 can be expressed in terms of subtraction.
368 C<!> and C<not> can be expressed in terms of boolean conversion, or
369 string or numerical conversion.
371 =item I<Concatenation>
373 can be expressed in terms of string conversion.
375 =item I<Comparison operations>
377 can be expressed in terms of its "spaceship" counterpart: either
378 C<E<lt>=E<gt>> or C<cmp>:
380 <, >, <=, >=, ==, != in terms of <=>
381 lt, gt, le, ge, eq, ne in terms of cmp
383 =item I<Copy operator>
385 can be expressed in terms of an assignment to the dereferenced value, if this
386 value is a scalar and not a reference.
392 The restriction for the comparison operation is that even if, for example,
393 `C<cmp>' should return a blessed reference, the autogenerated `C<lt>'
394 function will produce only a standard logical value based on the
395 numerical value of the result of `C<cmp>'. In particular, a working
396 numeric conversion is needed in this case (possibly expressed in terms of
399 Similarly, C<.=> and C<x=> operators lose their mathemagical properties
400 if the string conversion substitution is applied.
402 When you chop() a mathemagical object it is promoted to a string and its
403 mathemagical properties are lost. The same can happen with other
406 =head1 Run-time Overloading
408 Since all C<use> directives are executed at compile-time, the only way to
409 change overloading during run-time is to
411 eval 'use overload "+" => \&addmethod';
415 eval 'no overload "+", "--", "<="';
417 though the use of these constructs during run-time is questionable.
419 =head1 Public functions
421 Package C<overload.pm> provides the following public functions:
425 =item overload::StrVal(arg)
427 Gives string value of C<arg> as in absence of stringify overloading.
429 =item overload::Overloaded(arg)
431 Returns true if C<arg> is subject to overloading of some operations.
433 =item overload::Method(obj,op)
435 Returns C<undef> or a reference to the method that implements C<op>.
439 =head1 IMPLEMENTATION
441 What follows is subject to change RSN.
443 The table of methods for all operations is cached as magic in the
444 symbol table hash for the package. The table is rechecked for changes due to
445 C<use overload>, C<no overload>, and @ISA only during
446 C<bless>ing; so if they are changed dynamically, you'll need an
447 additional fake C<bless>ing to update the table.
449 (Every SVish thing has a magic queue, and magic is an entry in that queue.
450 This is how a single variable may participate in multiple forms of magic
451 simultaneously. For instance, environment variables regularly have two
452 forms at once: their %ENV magic and their taint magic.)
454 If an object belongs to a package using overload, it carries a special
455 flag. Thus the only speed penalty during arithmetic operations without
456 overloading is the checking of this flag.
458 In fact, if C<use overload> is not present, there is almost no overhead for
459 overloadable operations, so most programs should not suffer measurable
460 performance penalties. A considerable effort was made to minimize the overhead
461 when overload is used and the current operation is overloadable but
462 the arguments in question do not belong to packages using overload. When
463 in doubt, test your speed with C<use overload> and without it. So far there
464 have been no reports of substantial speed degradation if Perl is compiled
465 with optimization turned on.
467 There is no size penalty for data if overload is not used.
469 Copying (C<$a=$b>) is shallow; however, a one-level-deep copying is
470 carried out before any operation that can imply an assignment to the
471 object $a (or $b) refers to, like C<$a++>. You can override this
472 behavior by defining your own copy constructor (see L<"Copy Constructor">).
474 It is expected that arguments to methods that are not explicitly supposed
475 to be changed are constant (but this is not enforced).
479 Ilya Zakharevich <F<ilya@math.mps.ohio-state.edu>>.
483 When Perl is run with the B<-Do> switch or its equivalent, overloading
484 induces diagnostic messages.
488 Because it is used for overloading, the per-package associative array
489 %OVERLOAD now has a special meaning in Perl.
491 As shipped, mathemagical properties are not inherited via the @ISA tree.
493 This document is confusing.