1overload(3pm)          Perl Programmers Reference Guide          overload(3pm)
2
3
4

NAME

6       overload - Package for overloading Perl operations
7

SYNOPSIS

9           package SomeThing;
10
11           use overload
12               '+' => \&myadd,
13               '-' => \&mysub;
14               # etc
15           ...
16
17           package main;
18           $a = SomeThing->new( 57 );
19           $b = 5 + $a;
20           ...
21           if (overload::Overloaded $b) {...}
22           ...
23           $strval = overload::StrVal $b;
24

DESCRIPTION

26       This pragma allows overloading of Perl's operators for a class.  To
27       overload built-in functions, see "Overriding Built-in Functions" in
28       perlsub instead.
29
30   Fundamentals
31       Declaration
32
33       Arguments of the "use overload" directive are (key, value) pairs.  For
34       the full set of legal keys, see "Overloadable Operations" below.
35
36       Operator implementations (the values) can be subroutines, references to
37       subroutines, or anonymous subroutines - in other words, anything legal
38       inside a "&{ ... }" call.  Values specified as strings are interpreted
39       as method names.  Thus
40
41           package Number;
42           use overload
43               "-" => "minus",
44               "*=" => \&muas,
45               '""' => sub { ...; };
46
47       declares that subtraction is to be implemented by method "minus()" in
48       the class "Number" (or one of its base classes), and that the function
49       "Number::muas()" is to be used for the assignment form of
50       multiplication, "*=".  It also defines an anonymous subroutine to
51       implement stringification: this is called whenever an object blessed
52       into the package "Number" is used in a string context (this subroutine
53       might, for example, return the number as a Roman numeral).
54
55       Calling Conventions and Magic Autogeneration
56
57       The following sample implementation of "minus()" (which assumes that
58       "Number" objects are simply blessed references to scalars) illustrates
59       the calling conventions:
60
61           package Number;
62           sub minus {
63               my ($self, $other, $swap) = @_;
64               my $result = $$self - $other;         # *
65               $result = -$result if $swap;
66               ref $result ? $result : bless \$result;
67           }
68           # * may recurse once - see table below
69
70       Three arguments are passed to all subroutines specified in the "use
71       overload" directive (with one exception - see "nomethod").  The first
72       of these is the operand providing the overloaded operator
73       implementation - in this case, the object whose "minus()" method is
74       being called.
75
76       The second argument is the other operand, or "undef" in the case of a
77       unary operator.
78
79       The third argument is set to TRUE if (and only if) the two operands
80       have been swapped.  Perl may do this to ensure that the first argument
81       ($self) is an object implementing the overloaded operation, in line
82       with general object calling conventions.  For example, if $x and $y are
83       "Number"s:
84
85           operation   |   generates a call to
86           ============|======================
87           $x - $y     |   minus($x, $y, '')
88           $x - 7      |   minus($x, 7, '')
89           7 - $x      |   minus($x, 7, 1)
90
91       Perl may also use "minus()" to implement other operators which have not
92       been specified in the "use overload" directive, according to the rules
93       for "Magic Autogeneration" described later.  For example, the "use
94       overload" above declared no subroutine for any of the operators "--",
95       "neg" (the overload key for unary minus), or "-=".  Thus
96
97           operation   |   generates a call to
98           ============|======================
99           -$x         |   minus($x, 0, 1)
100           $x--        |   minus($x, 1, undef)
101           $x -= 3     |   minus($x, 3, undef)
102
103       Note the "undef"s: where autogeneration results in the method for a
104       standard operator which does not change either of its operands, such as
105       "-", being used to implement an operator which changes the operand
106       ("mutators": here, "--" and "-="), Perl passes undef as the third
107       argument.  This still evaluates as FALSE, consistent with the fact that
108       the operands have not been swapped, but gives the subroutine a chance
109       to alter its behaviour in these cases.
110
111       In all the above examples, "minus()" is required only to return the
112       result of the subtraction: Perl takes care of the assignment to $x.  In
113       fact, such methods should not modify their operands, even if "undef" is
114       passed as the third argument (see "Overloadable Operations").
115
116       The same is not true of implementations of "++" and "--": these are
117       expected to modify their operand.  An appropriate implementation of
118       "--" might look like
119
120           use overload '--' => "decr",
121               # ...
122           sub decr { --${$_[0]}; }
123
124       Mathemagic, Mutators, and Copy Constructors
125
126       The term 'mathemagic' describes the overloaded implementation of
127       mathematical operators.  Mathemagical operations raise an issue.
128       Consider the code:
129
130           $a = $b;
131           --$a;
132
133       If $a and $b are scalars then after these statements
134
135           $a == $b - 1
136
137       An object, however, is a reference to blessed data, so if $a and $b are
138       objects then the assignment "$a = $b" copies only the reference,
139       leaving $a and $b referring to the same object data.  One might
140       therefore expect the operation "--$a" to decrement $b as well as $a.
141       However, this would not be consistent with how we expect the
142       mathematical operators to work.
143
144       Perl resolves this dilemma by transparently calling a copy constructor
145       before calling a method defined to implement a mutator ("--", "+=", and
146       so on.).  In the above example, when Perl reaches the decrement
147       statement, it makes a copy of the object data in $a and assigns to $a a
148       reference to the copied data.  Only then does it call "decr()", which
149       alters the copied data, leaving $b unchanged.  Thus the object metaphor
150       is preserved as far as possible, while mathemagical operations still
151       work according to the arithmetic metaphor.
152
153       Note: the preceding paragraph describes what happens when Perl
154       autogenerates the copy constructor for an object based on a scalar.
155       For other cases, see "Copy Constructor".
156
157   Overloadable Operations
158       The complete list of keys that can be specified in the "use overload"
159       directive are given, separated by spaces, in the values of the hash
160       %overload::ops:
161
162        with_assign      => '+ - * / % ** << >> x .',
163        assign           => '+= -= *= /= %= **= <<= >>= x= .=',
164        num_comparison   => '< <= > >= == !=',
165        '3way_comparison'=> '<=> cmp',
166        str_comparison   => 'lt le gt ge eq ne',
167        binary           => '& &= | |= ^ ^=',
168        unary            => 'neg ! ~',
169        mutators         => '++ --',
170        func             => 'atan2 cos sin exp abs log sqrt int',
171        conversion       => 'bool "" 0+ qr',
172        iterators        => '<>',
173        filetest         => '-X',
174        dereferencing    => '${} @{} %{} &{} *{}',
175        matching         => '~~',
176        special          => 'nomethod fallback ='
177
178       Most of the overloadable operators map one-to-one to these keys.
179       Exceptions, including additional overloadable operations not apparent
180       from this hash, are included in the notes which follow.
181
182       A warning is issued if an attempt is made to register an operator not
183       found above.
184
185       ·    "not"
186
187            The operator "not" is not a valid key for "use overload".
188            However, if the operator "!" is overloaded then the same
189            implementation will be used for "not" (since the two operators
190            differ only in precedence).
191
192       ·    "neg"
193
194            The key "neg" is used for unary minus to disambiguate it from
195            binary "-".
196
197       ·    "++", "--"
198
199            Assuming they are to behave analogously to Perl's "++" and "--",
200            overloaded implementations of these operators are required to
201            mutate their operands.
202
203            No distinction is made between prefix and postfix forms of the
204            increment and decrement operators: these differ only in the point
205            at which Perl calls the associated subroutine when evaluating an
206            expression.
207
208       ·    Assignments
209
210                +=  -=  *=  /=  %=  **=  <<=  >>=  x=  .=
211                &=  |=  ^=
212
213            Simple assignment is not overloadable (the '=' key is used for the
214            "Copy Constructor").  Perl does have a way to make assignments to
215            an object do whatever you want, but this involves using tie(), not
216            overload - see "tie" in perlfunc and the "COOKBOOK" examples
217            below.
218
219            The subroutine for the assignment variant of an operator is
220            required only to return the result of the operation.  It is
221            permitted to change the value of its operand (this is safe because
222            Perl calls the copy constructor first), but this is optional since
223            Perl assigns the returned value to the left-hand operand anyway.
224
225            An object that overloads an assignment operator does so only in
226            respect of assignments to that object.  In other words, Perl never
227            calls the corresponding methods with the third argument (the
228            "swap" argument) set to TRUE.  For example, the operation
229
230                $a *= $b
231
232            cannot lead to $b's implementation of "*=" being called, even if
233            $a is a scalar.  (It can, however, generate a call to $b's method
234            for "*").
235
236       ·    Non-mutators with a mutator variant
237
238                 +  -  *  /  %  **  <<  >>  x  .
239                 &  |  ^
240
241            As described above, Perl may call methods for operators like "+"
242            and "&" in the course of implementing missing operations like
243            "++", "+=", and "&=".  While these methods may detect this usage
244            by testing the definedness of the third argument, they should in
245            all cases avoid changing their operands.  This is because Perl
246            does not call the copy constructor before invoking these methods.
247
248       ·    "int"
249
250            Traditionally, the Perl function "int" rounds to 0 (see "int" in
251            perlfunc), and so for floating-point-like types one should follow
252            the same semantic.
253
254       ·    String, numeric, boolean, and regexp conversions
255
256                ""  0+  bool
257
258            These conversions are invoked according to context as necessary.
259            For example, the subroutine for '""' (stringify) may be used where
260            the overloaded object is passed as an argument to "print", and
261            that for 'bool' where it is tested in the condition of a flow
262            control statement (like "while") or the ternary "?:" operation.
263
264            Of course, in contexts like, for example, "$obj + 1", Perl will
265            invoke $obj's implementation of "+" rather than (in this example)
266            converting $obj to a number using the numify method '0+' (an
267            exception to this is when no method has been provided for '+' and
268            "fallback" is set to TRUE).
269
270            The subroutines for '""', '0+', and 'bool' can return any
271            arbitrary Perl value.  If the corresponding operation for this
272            value is overloaded too, the operation will be called again with
273            this value.
274
275            As a special case if the overload returns the object itself then
276            it will be used directly.  An overloaded conversion returning the
277            object is probably a bug, because you're likely to get something
278            that looks like "YourPackage=HASH(0x8172b34)".
279
280                qr
281
282            The subroutine for 'qr' is used wherever the object is
283            interpolated into or used as a regexp, including when it appears
284            on the RHS of a "=~" or "!~" operator.
285
286            "qr" must return a compiled regexp, or a ref to a compiled regexp
287            (such as "qr//" returns), and any further overloading on the
288            return value will be ignored.
289
290       ·    Iteration
291
292            If "<>" is overloaded then the same implementation is used for
293            both the read-filehandle syntax "<$var>" and globbing syntax
294            "<${var}>".
295
296            BUGS Even in list context, the iterator is currently called only
297            once and with scalar context.
298
299       ·    File tests
300
301            The key '-X' is used to specify a subroutine to handle all the
302            filetest operators ("-f", "-x", and so on: see "-X" in perlfunc
303            for the full list); it is not possible to overload any filetest
304            operator individually.  To distinguish them, the letter following
305            the '-' is passed as the second argument (that is, in the slot
306            that for binary operators is used to pass the second operand).
307
308            Calling an overloaded filetest operator does not affect the stat
309            value associated with the special filehandle "_".  It still refers
310            to the result of the last "stat", "lstat" or unoverloaded
311            filetest.
312
313            This overload was introduced in Perl 5.12.
314
315       ·    Matching
316
317            The key "~~" allows you to override the smart matching logic used
318            by the "~~" operator and the switch construct ("given"/"when").
319            See "Switch Statements" in perlsyn and feature.
320
321            Unusually, the overloaded implementation of the smart match
322            operator does not get full control of the smart match behaviour.
323            In particular, in the following code:
324
325                package Foo;
326                use overload '~~' => 'match';
327
328                my $obj =  Foo->new();
329                $obj ~~ [ 1,2,3 ];
330
331            the smart match does not invoke the method call like this:
332
333                $obj->match([1,2,3],0);
334
335            rather, the smart match distributive rule takes precedence, so
336            $obj is smart matched against each array element in turn until a
337            match is found, so you may see between one and three of these
338            calls instead:
339
340                $obj->match(1,0);
341                $obj->match(2,0);
342                $obj->match(3,0);
343
344            Consult the match table in  "Smartmatch Operator" in perlop for
345            details of when overloading is invoked.
346
347       ·    Dereferencing
348
349                ${}  @{}  %{}  &{}  *{}
350
351            If these operators are not explicitly overloaded then they work in
352            the normal way, yielding the underlying scalar, array, or whatever
353            stores the object data (or the appropriate error message if the
354            dereference operator doesn't match it).  Defining a catch-all
355            'nomethod' (see below) makes no difference to this as the catch-
356            all function will not be called to implement a missing dereference
357            operator.
358
359            If a dereference operator is overloaded then it must return a
360            reference of the appropriate type (for example, the subroutine for
361            key '${}' should return a reference to a scalar, not a scalar), or
362            another object which overloads the operator: that is, the
363            subroutine only determines what is dereferenced and the actual
364            dereferencing is left to Perl.  As a special case, if the
365            subroutine returns the object itself then it will not be called
366            again - avoiding infinite recursion.
367
368       ·    Special
369
370                nomethod  fallback  =
371
372            See "Special Keys for "use overload"".
373
374   Magic Autogeneration
375       If a method for an operation is not found then Perl tries to
376       autogenerate a substitute implementation from the operations that have
377       been defined.
378
379       Note: the behaviour described in this section can be disabled by
380       setting "fallback" to FALSE (see "fallback").
381
382       In the following tables, numbers indicate priority.  For example, the
383       table below states that, if no implementation for '!' has been defined
384       then Perl will implement it using 'bool' (that is, by inverting the
385       value returned by the method for 'bool'); if boolean conversion is also
386       unimplemented then Perl will use '0+' or, failing that, '""'.
387
388           operator | can be autogenerated from
389                    |
390                    | 0+   ""   bool   .   x
391           =========|==========================
392              0+    |       1     2
393              ""    |  1          2
394              bool  |  1    2
395              int   |  1    2     3
396              !     |  2    3     1
397              qr    |  2    1     3
398              .     |  2    1     3
399              x     |  2    1     3
400              .=    |  3    2     4    1
401              x=    |  3    2     4        1
402              <>    |  2    1     3
403              -X    |  2    1     3
404
405       Note: The iterator ('<>') and file test ('-X') operators work as
406       normal: if the operand is not a blessed glob or IO reference then it is
407       converted to a string (using the method for '""', '0+', or 'bool') to
408       be interpreted as a glob or filename.
409
410           operator | can be autogenerated from
411                    |
412                    |  <   <=>   neg   -=    -
413           =========|==========================
414              neg   |                        1
415              -=    |                        1
416              --    |                   1    2
417              abs   | a1    a2    b1        b2    [*]
418              <     |        1
419              <=    |        1
420              >     |        1
421              >=    |        1
422              ==    |        1
423              !=    |        1
424
425           * one from [a1, a2] and one from [b1, b2]
426
427       Just as numeric comparisons can be autogenerated from the method for
428       '<=>', string comparisons can be autogenerated from that for 'cmp':
429
430            operators          |  can be autogenerated from
431           ====================|===========================
432            lt gt le ge eq ne  |  cmp
433
434       Similarly, autogeneration for keys '+=' and '++' is analogous to '-='
435       and '--' above:
436
437           operator | can be autogenerated from
438                    |
439                    |  +=    +
440           =========|==========================
441               +=   |        1
442               ++   |   1    2
443
444       And other assignment variations are analogous to '+=' and '-=' (and
445       similar to '.=' and 'x=' above):
446
447                     operator ||  *= /= %= **= <<= >>= &= ^= |=
448           -------------------||--------------------------------
449           autogenerated from ||  *  /  %  **  <<  >>  &  ^  |
450
451       Note also that the copy constructor (key '=') may be autogenerated, but
452       only for objects based on scalars.  See "Copy Constructor".
453
454       Minimal Set of Overloaded Operations
455
456       Since some operations can be automatically generated from others, there
457       is a minimal set of operations that need to be overloaded in order to
458       have the complete set of overloaded operations at one's disposal.  Of
459       course, the autogenerated operations may not do exactly what the user
460       expects.  The minimal set is:
461
462           + - * / % ** << >> x
463           <=> cmp
464           & | ^ ~
465           atan2 cos sin exp log sqrt int
466           "" 0+ bool
467           ~~
468
469       Of the conversions, only one of string, boolean or numeric is needed
470       because each can be generated from either of the other two.
471
472   Special Keys for "use overload"
473       "nomethod"
474
475       The 'nomethod' key is used to specify a catch-all function to be called
476       for any operator that is not individually overloaded.  The specified
477       function will be passed four parameters.  The first three arguments
478       coincide with those that would have been passed to the corresponding
479       method if it had been defined.  The fourth argument is the "use
480       overload" key for that missing method.
481
482       For example, if $a is an object blessed into a package declaring
483
484           use overload 'nomethod' => 'catch_all', # ...
485
486       then the operation
487
488           3 + $a
489
490       could (unless a method is specifically declared for the key '+') result
491       in a call
492
493           catch_all($a, 3, 1, '+')
494
495       See "How Perl Chooses an Operator Implementation".
496
497       "fallback"
498
499       The value assigned to the key 'fallback' tells Perl how hard it should
500       try to find an alternative way to implement a missing operator.
501
502       ·   defined, but FALSE
503
504               use overload "fallback" => 0, # ... ;
505
506           This disables "Magic Autogeneration".
507
508       ·   "undef"
509
510           In the default case where no value is explicitly assigned to
511           "fallback", magic autogeneration is enabled.
512
513       ·   TRUE
514
515           The same as for "undef", but if a missing operator cannot be
516           autogenerated then, instead of issuing an error message, Perl is
517           allowed to revert to what it would have done for that operator if
518           there had been no "use overload" directive.
519
520           Note: in most cases, particularly the "Copy Constructor", this is
521           unlikely to be appropriate behaviour.
522
523       See "How Perl Chooses an Operator Implementation".
524
525       Copy Constructor
526
527       As mentioned above, this operation is called when a mutator is applied
528       to a reference that shares its object with some other reference.  For
529       example, if $b is mathemagical, and '++' is overloaded with 'incr', and
530       '=' is overloaded with 'clone', then the code
531
532           $a = $b;
533           # ... (other code which does not modify $a or $b) ...
534           ++$b;
535
536       would be executed in a manner equivalent to
537
538           $a = $b;
539           # ...
540           $b = $b->clone(undef, "");
541           $b->incr(undef, "");
542
543       Note:
544
545       ·   The subroutine for '=' does not overload the Perl assignment
546           operator: it is used only to allow mutators to work as described
547           here.  (See "Assignments" above.)
548
549       ·   As for other operations, the subroutine implementing '=' is passed
550           three arguments, though the last two are always "undef" and ''.
551
552       ·   The copy constructor is called only before a call to a function
553           declared to implement a mutator, for example, if "++$b;" in the
554           code above is effected via a method declared for key '++' (or
555           'nomethod', passed '++' as the fourth argument) or, by
556           autogeneration, '+='.  It is not called if the increment operation
557           is effected by a call to the method for '+' since, in the
558           equivalent code,
559
560               $a = $b;
561               $b = $b + 1;
562
563           the data referred to by $a is unchanged by the assignment to $b of
564           a reference to new object data.
565
566       ·   The copy constructor is not called if Perl determines that it is
567           unnecessary because there is no other reference to the data being
568           modified.
569
570       ·   If 'fallback' is undefined or TRUE then a copy constructor can be
571           autogenerated, but only for objects based on scalars.  In other
572           cases it needs to be defined explicitly.  Where an object's data is
573           stored as, for example, an array of scalars, the following might be
574           appropriate:
575
576               use overload '=' => sub { bless [ @{$_[0]} ] },  # ...
577
578       ·   If 'fallback' is TRUE and no copy constructor is defined then, for
579           objects not based on scalars, Perl may silently fall back on simple
580           assignment - that is, assignment of the object reference.  In
581           effect, this disables the copy constructor mechanism since no new
582           copy of the object data is created.  This is almost certainly not
583           what you want.  (It is, however, consistent: for example, Perl's
584           fallback for the "++" operator is to increment the reference
585           itself.)
586
587   How Perl Chooses an Operator Implementation
588       Which is checked first, "nomethod" or "fallback"?  If the two operands
589       of an operator are of different types and both overload the operator,
590       which implementation is used?  The following are the precedence rules:
591
592       1.  If the first operand has declared a subroutine to overload the
593           operator then use that implementation.
594
595       2.  Otherwise, if fallback is TRUE or undefined for the first operand
596           then see if the rules for autogeneration allows another of its
597           operators to be used instead.
598
599       3.  Unless the operator is an assignment ("+=", "-=", etc.), repeat
600           step (1) in respect of the second operand.
601
602       4.  Repeat Step (2) in respect of the second operand.
603
604       5.  If the first operand has a "nomethod" method then use that.
605
606       6.  If the second operand has a "nomethod" method then use that.
607
608       7.  If "fallback" is TRUE for both operands then perform the usual
609           operation for the operator, treating the operands as numbers,
610           strings, or booleans as appropriate for the operator (see note).
611
612       8.  Nothing worked - die.
613
614       Where there is only one operand (or only one operand with overloading)
615       the checks in respect of the other operand above are skipped.
616
617       There are exceptions to the above rules for dereference operations
618       (which, if Step 1 fails, always fall back to the normal, built-in
619       implementations - see Dereferencing), and for "~~" (which has its own
620       set of rules - see "Matching" under "Overloadable Operations" above).
621
622       Note on Step 7: some operators have a different semantic depending on
623       the type of their operands.  As there is no way to instruct Perl to
624       treat the operands as, e.g., numbers instead of strings, the result
625       here may not be what you expect.  See "BUGS AND PITFALLS".
626
627   Losing Overloading
628       The restriction for the comparison operation is that even if, for
629       example, "cmp" should return a blessed reference, the autogenerated
630       "lt" function will produce only a standard logical value based on the
631       numerical value of the result of "cmp".  In particular, a working
632       numeric conversion is needed in this case (possibly expressed in terms
633       of other conversions).
634
635       Similarly, ".="  and "x=" operators lose their mathemagical properties
636       if the string conversion substitution is applied.
637
638       When you chop() a mathemagical object it is promoted to a string and
639       its mathemagical properties are lost.  The same can happen with other
640       operations as well.
641
642   Inheritance and Overloading
643       Overloading respects inheritance via the @ISA hierarchy.  Inheritance
644       interacts with overloading in two ways.
645
646       Method names in the "use overload" directive
647           If "value" in
648
649             use overload key => value;
650
651           is a string, it is interpreted as a method name - which may (in the
652           usual way) be inherited from another class.
653
654       Overloading of an operation is inherited by derived classes
655           Any class derived from an overloaded class is also overloaded and
656           inherits its operator implementations.  If the same operator is
657           overloaded in more than one ancestor then the implementation is
658           determined by the usual inheritance rules.
659
660           For example, if "A" inherits from "B" and "C" (in that order), "B"
661           overloads "+" with "\&D::plus_sub", and "C" overloads "+" by
662           "plus_meth", then the subroutine "D::plus_sub" will be called to
663           implement operation "+" for an object in package "A".
664
665       Note that since the value of the "fallback" key is not a subroutine,
666       its inheritance is not governed by the above rules.  In the current
667       implementation, the value of "fallback" in the first overloaded
668       ancestor is used, but this is accidental and subject to change.
669
670   Run-time Overloading
671       Since all "use" directives are executed at compile-time, the only way
672       to change overloading during run-time is to
673
674           eval 'use overload "+" => \&addmethod';
675
676       You can also use
677
678           eval 'no overload "+", "--", "<="';
679
680       though the use of these constructs during run-time is questionable.
681
682   Public Functions
683       Package "overload.pm" provides the following public functions:
684
685       overload::StrVal(arg)
686            Gives the string value of "arg" as in the absence of stringify
687            overloading.  If you are using this to get the address of a
688            reference (useful for checking if two references point to the same
689            thing) then you may be better off using "Scalar::Util::refaddr()",
690            which is faster.
691
692       overload::Overloaded(arg)
693            Returns true if "arg" is subject to overloading of some
694            operations.
695
696       overload::Method(obj,op)
697            Returns "undef" or a reference to the method that implements "op".
698
699   Overloading Constants
700       For some applications, the Perl parser mangles constants too much.  It
701       is possible to hook into this process via "overload::constant()" and
702       "overload::remove_constant()" functions.
703
704       These functions take a hash as an argument.  The recognized keys of
705       this hash are:
706
707       integer to overload integer constants,
708
709       float   to overload floating point constants,
710
711       binary  to overload octal and hexadecimal constants,
712
713       q       to overload "q"-quoted strings, constant pieces of "qq"- and
714               "qx"-quoted strings and here-documents,
715
716       qr      to overload constant pieces of regular expressions.
717
718       The corresponding values are references to functions which take three
719       arguments: the first one is the initial string form of the constant,
720       the second one is how Perl interprets this constant, the third one is
721       how the constant is used.  Note that the initial string form does not
722       contain string delimiters, and has backslashes in backslash-delimiter
723       combinations stripped (thus the value of delimiter is not relevant for
724       processing of this string).  The return value of this function is how
725       this constant is going to be interpreted by Perl.  The third argument
726       is undefined unless for overloaded "q"- and "qr"- constants, it is "q"
727       in single-quote context (comes from strings, regular expressions, and
728       single-quote HERE documents), it is "tr" for arguments of "tr"/"y"
729       operators, it is "s" for right-hand side of "s"-operator, and it is
730       "qq" otherwise.
731
732       Since an expression "ab$cd,," is just a shortcut for 'ab' . $cd . ',,',
733       it is expected that overloaded constant strings are equipped with
734       reasonable overloaded catenation operator, otherwise absurd results
735       will result.  Similarly, negative numbers are considered as negations
736       of positive constants.
737
738       Note that it is probably meaningless to call the functions
739       overload::constant() and overload::remove_constant() from anywhere but
740       import() and unimport() methods.  From these methods they may be called
741       as
742
743           sub import {
744              shift;
745              return unless @_;
746              die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
747              overload::constant integer => sub {Math::BigInt->new(shift)};
748           }
749

IMPLEMENTATION

751       What follows is subject to change RSN.
752
753       The table of methods for all operations is cached in magic for the
754       symbol table hash for the package.  The cache is invalidated during
755       processing of "use overload", "no overload", new function definitions,
756       and changes in @ISA.  However, this invalidation remains unprocessed
757       until the next "bless"ing into the package.  Hence if you want to
758       change overloading structure dynamically, you'll need an additional
759       (fake) "bless"ing to update the table.
760
761       (Every SVish thing has a magic queue, and magic is an entry in that
762       queue.  This is how a single variable may participate in multiple forms
763       of magic simultaneously.  For instance, environment variables regularly
764       have two forms at once: their %ENV magic and their taint magic.
765       However, the magic which implements overloading is applied to the
766       stashes, which are rarely used directly, thus should not slow down
767       Perl.)
768
769       If an object belongs to a package using overload, it carries a special
770       flag.  Thus the only speed penalty during arithmetic operations without
771       overloading is the checking of this flag.
772
773       In fact, if "use overload" is not present, there is almost no overhead
774       for overloadable operations, so most programs should not suffer
775       measurable performance penalties.  A considerable effort was made to
776       minimize the overhead when overload is used in some package, but the
777       arguments in question do not belong to packages using overload.  When
778       in doubt, test your speed with "use overload" and without it.  So far
779       there have been no reports of substantial speed degradation if Perl is
780       compiled with optimization turned on.
781
782       There is no size penalty for data if overload is not used.  The only
783       size penalty if overload is used in some package is that all the
784       packages acquire a magic during the next "bless"ing into the package.
785       This magic is three-words-long for packages without overloading, and
786       carries the cache table if the package is overloaded.
787
788       It is expected that arguments to methods that are not explicitly
789       supposed to be changed are constant (but this is not enforced).
790

COOKBOOK

792       Please add examples to what follows!
793
794   Two-face Scalars
795       Put this in two_face.pm in your Perl library directory:
796
797         package two_face;             # Scalars with separate string and
798                                       # numeric values.
799         sub new { my $p = shift; bless [@_], $p }
800         use overload '""' => \&str, '0+' => \&num, fallback => 1;
801         sub num {shift->[1]}
802         sub str {shift->[0]}
803
804       Use it as follows:
805
806         require two_face;
807         my $seven = two_face->new("vii", 7);
808         printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
809         print "seven contains 'i'\n" if $seven =~ /i/;
810
811       (The second line creates a scalar which has both a string value, and a
812       numeric value.)  This prints:
813
814         seven=vii, seven=7, eight=8
815         seven contains 'i'
816
817   Two-face References
818       Suppose you want to create an object which is accessible as both an
819       array reference and a hash reference.
820
821         package two_refs;
822         use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
823         sub new {
824           my $p = shift;
825           bless \ [@_], $p;
826         }
827         sub gethash {
828           my %h;
829           my $self = shift;
830           tie %h, ref $self, $self;
831           \%h;
832         }
833
834         sub TIEHASH { my $p = shift; bless \ shift, $p }
835         my %fields;
836         my $i = 0;
837         $fields{$_} = $i++ foreach qw{zero one two three};
838         sub STORE {
839           my $self = ${shift()};
840           my $key = $fields{shift()};
841           defined $key or die "Out of band access";
842           $$self->[$key] = shift;
843         }
844         sub FETCH {
845           my $self = ${shift()};
846           my $key = $fields{shift()};
847           defined $key or die "Out of band access";
848           $$self->[$key];
849         }
850
851       Now one can access an object using both the array and hash syntax:
852
853         my $bar = two_refs->new(3,4,5,6);
854         $bar->[2] = 11;
855         $bar->{two} == 11 or die 'bad hash fetch';
856
857       Note several important features of this example.  First of all, the
858       actual type of $bar is a scalar reference, and we do not overload the
859       scalar dereference.  Thus we can get the actual non-overloaded contents
860       of $bar by just using $$bar (what we do in functions which overload
861       dereference).  Similarly, the object returned by the TIEHASH() method
862       is a scalar reference.
863
864       Second, we create a new tied hash each time the hash syntax is used.
865       This allows us not to worry about a possibility of a reference loop,
866       which would lead to a memory leak.
867
868       Both these problems can be cured.  Say, if we want to overload hash
869       dereference on a reference to an object which is implemented as a hash
870       itself, the only problem one has to circumvent is how to access this
871       actual hash (as opposed to the virtual hash exhibited by the overloaded
872       dereference operator).  Here is one possible fetching routine:
873
874         sub access_hash {
875           my ($self, $key) = (shift, shift);
876           my $class = ref $self;
877           bless $self, 'overload::dummy'; # Disable overloading of %{}
878           my $out = $self->{$key};
879           bless $self, $class;        # Restore overloading
880           $out;
881         }
882
883       To remove creation of the tied hash on each access, one may an extra
884       level of indirection which allows a non-circular structure of
885       references:
886
887         package two_refs1;
888         use overload '%{}' => sub { ${shift()}->[1] },
889                      '@{}' => sub { ${shift()}->[0] };
890         sub new {
891           my $p = shift;
892           my $a = [@_];
893           my %h;
894           tie %h, $p, $a;
895           bless \ [$a, \%h], $p;
896         }
897         sub gethash {
898           my %h;
899           my $self = shift;
900           tie %h, ref $self, $self;
901           \%h;
902         }
903
904         sub TIEHASH { my $p = shift; bless \ shift, $p }
905         my %fields;
906         my $i = 0;
907         $fields{$_} = $i++ foreach qw{zero one two three};
908         sub STORE {
909           my $a = ${shift()};
910           my $key = $fields{shift()};
911           defined $key or die "Out of band access";
912           $a->[$key] = shift;
913         }
914         sub FETCH {
915           my $a = ${shift()};
916           my $key = $fields{shift()};
917           defined $key or die "Out of band access";
918           $a->[$key];
919         }
920
921       Now if $baz is overloaded like this, then $baz is a reference to a
922       reference to the intermediate array, which keeps a reference to an
923       actual array, and the access hash.  The tie()ing object for the access
924       hash is a reference to a reference to the actual array, so
925
926       ·   There are no loops of references.
927
928       ·   Both "objects" which are blessed into the class "two_refs1" are
929           references to a reference to an array, thus references to a scalar.
930           Thus the accessor expression "$$foo->[$ind]" involves no overloaded
931           operations.
932
933   Symbolic Calculator
934       Put this in symbolic.pm in your Perl library directory:
935
936         package symbolic;             # Primitive symbolic calculator
937         use overload nomethod => \&wrap;
938
939         sub new { shift; bless ['n', @_] }
940         sub wrap {
941           my ($obj, $other, $inv, $meth) = @_;
942           ($obj, $other) = ($other, $obj) if $inv;
943           bless [$meth, $obj, $other];
944         }
945
946       This module is very unusual as overloaded modules go: it does not
947       provide any usual overloaded operators, instead it provides an
948       implementation for "nomethod".  In this example the "nomethod"
949       subroutine returns an object which encapsulates operations done over
950       the objects: "symbolic->new(3)" contains "['n', 3]", "2 +
951       symbolic->new(3)" contains "['+', 2, ['n', 3]]".
952
953       Here is an example of the script which "calculates" the side of
954       circumscribed octagon using the above package:
955
956         require symbolic;
957         my $iter = 1;                 # 2**($iter+2) = 8
958         my $side = symbolic->new(1);
959         my $cnt = $iter;
960
961         while ($cnt--) {
962           $side = (sqrt(1 + $side**2) - 1)/$side;
963         }
964         print "OK\n";
965
966       The value of $side is
967
968         ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
969                              undef], 1], ['n', 1]]
970
971       Note that while we obtained this value using a nice little script,
972       there is no simple way to use this value.  In fact this value may be
973       inspected in debugger (see perldebug), but only if "bareStringify"
974       Option is set, and not via "p" command.
975
976       If one attempts to print this value, then the overloaded operator ""
977       will be called, which will call "nomethod" operator.  The result of
978       this operator will be stringified again, but this result is again of
979       type "symbolic", which will lead to an infinite loop.
980
981       Add a pretty-printer method to the module symbolic.pm:
982
983         sub pretty {
984           my ($meth, $a, $b) = @{+shift};
985           $a = 'u' unless defined $a;
986           $b = 'u' unless defined $b;
987           $a = $a->pretty if ref $a;
988           $b = $b->pretty if ref $b;
989           "[$meth $a $b]";
990         }
991
992       Now one can finish the script by
993
994         print "side = ", $side->pretty, "\n";
995
996       The method "pretty" is doing object-to-string conversion, so it is
997       natural to overload the operator "" using this method.  However, inside
998       such a method it is not necessary to pretty-print the components $a and
999       $b of an object.  In the above subroutine "[$meth $a $b]" is a
1000       catenation of some strings and components $a and $b.  If these
1001       components use overloading, the catenation operator will look for an
1002       overloaded operator "."; if not present, it will look for an overloaded
1003       operator "".  Thus it is enough to use
1004
1005         use overload nomethod => \&wrap, '""' => \&str;
1006         sub str {
1007           my ($meth, $a, $b) = @{+shift};
1008           $a = 'u' unless defined $a;
1009           $b = 'u' unless defined $b;
1010           "[$meth $a $b]";
1011         }
1012
1013       Now one can change the last line of the script to
1014
1015         print "side = $side\n";
1016
1017       which outputs
1018
1019         side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
1020
1021       and one can inspect the value in debugger using all the possible
1022       methods.
1023
1024       Something is still amiss: consider the loop variable $cnt of the
1025       script.  It was a number, not an object.  We cannot make this value of
1026       type "symbolic", since then the loop will not terminate.
1027
1028       Indeed, to terminate the cycle, the $cnt should become false.  However,
1029       the operator "bool" for checking falsity is overloaded (this time via
1030       overloaded ""), and returns a long string, thus any object of type
1031       "symbolic" is true.  To overcome this, we need a way to compare an
1032       object to 0.  In fact, it is easier to write a numeric conversion
1033       routine.
1034
1035       Here is the text of symbolic.pm with such a routine added (and slightly
1036       modified str()):
1037
1038         package symbolic;             # Primitive symbolic calculator
1039         use overload
1040           nomethod => \&wrap, '""' => \&str, '0+' => \&num;
1041
1042         sub new { shift; bless ['n', @_] }
1043         sub wrap {
1044           my ($obj, $other, $inv, $meth) = @_;
1045           ($obj, $other) = ($other, $obj) if $inv;
1046           bless [$meth, $obj, $other];
1047         }
1048         sub str {
1049           my ($meth, $a, $b) = @{+shift};
1050           $a = 'u' unless defined $a;
1051           if (defined $b) {
1052             "[$meth $a $b]";
1053           } else {
1054             "[$meth $a]";
1055           }
1056         }
1057         my %subr = ( n => sub {$_[0]},
1058                      sqrt => sub {sqrt $_[0]},
1059                      '-' => sub {shift() - shift()},
1060                      '+' => sub {shift() + shift()},
1061                      '/' => sub {shift() / shift()},
1062                      '*' => sub {shift() * shift()},
1063                      '**' => sub {shift() ** shift()},
1064                    );
1065         sub num {
1066           my ($meth, $a, $b) = @{+shift};
1067           my $subr = $subr{$meth}
1068             or die "Do not know how to ($meth) in symbolic";
1069           $a = $a->num if ref $a eq __PACKAGE__;
1070           $b = $b->num if ref $b eq __PACKAGE__;
1071           $subr->($a,$b);
1072         }
1073
1074       All the work of numeric conversion is done in %subr and num().  Of
1075       course, %subr is not complete, it contains only operators used in the
1076       example below.  Here is the extra-credit question: why do we need an
1077       explicit recursion in num()?  (Answer is at the end of this section.)
1078
1079       Use this module like this:
1080
1081         require symbolic;
1082         my $iter = symbolic->new(2);  # 16-gon
1083         my $side = symbolic->new(1);
1084         my $cnt = $iter;
1085
1086         while ($cnt) {
1087           $cnt = $cnt - 1;            # Mutator '--' not implemented
1088           $side = (sqrt(1 + $side**2) - 1)/$side;
1089         }
1090         printf "%s=%f\n", $side, $side;
1091         printf "pi=%f\n", $side*(2**($iter+2));
1092
1093       It prints (without so many line breaks)
1094
1095         [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
1096                                 [n 1]] 2]]] 1]
1097            [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1098         pi=3.182598
1099
1100       The above module is very primitive.  It does not implement mutator
1101       methods ("++", "-=" and so on), does not do deep copying (not required
1102       without mutators!), and implements only those arithmetic operations
1103       which are used in the example.
1104
1105       To implement most arithmetic operations is easy; one should just use
1106       the tables of operations, and change the code which fills %subr to
1107
1108         my %subr = ( 'n' => sub {$_[0]} );
1109         foreach my $op (split " ", $overload::ops{with_assign}) {
1110           $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1111         }
1112         my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1113         foreach my $op (split " ", "@overload::ops{ @bins }") {
1114           $subr{$op} = eval "sub {shift() $op shift()}";
1115         }
1116         foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1117           print "defining '$op'\n";
1118           $subr{$op} = eval "sub {$op shift()}";
1119         }
1120
1121       Since subroutines implementing assignment operators are not required to
1122       modify their operands (see "Overloadable Operations" above), we do not
1123       need anything special to make "+=" and friends work, besides adding
1124       these operators to %subr and defining a copy constructor (needed since
1125       Perl has no way to know that the implementation of '+=' does not mutate
1126       the argument - see "Copy Constructor").
1127
1128       To implement a copy constructor, add "'=' => \&cpy" to "use overload"
1129       line, and code (this code assumes that mutators change things one level
1130       deep only, so recursive copying is not needed):
1131
1132         sub cpy {
1133           my $self = shift;
1134           bless [@$self], ref $self;
1135         }
1136
1137       To make "++" and "--" work, we need to implement actual mutators,
1138       either directly, or in "nomethod".  We continue to do things inside
1139       "nomethod", thus add
1140
1141           if ($meth eq '++' or $meth eq '--') {
1142             @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1143             return $obj;
1144           }
1145
1146       after the first line of wrap().  This is not a most effective
1147       implementation, one may consider
1148
1149         sub inc { $_[0] = bless ['++', shift, 1]; }
1150
1151       instead.
1152
1153       As a final remark, note that one can fill %subr by
1154
1155         my %subr = ( 'n' => sub {$_[0]} );
1156         foreach my $op (split " ", $overload::ops{with_assign}) {
1157           $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1158         }
1159         my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1160         foreach my $op (split " ", "@overload::ops{ @bins }") {
1161           $subr{$op} = eval "sub {shift() $op shift()}";
1162         }
1163         foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1164           $subr{$op} = eval "sub {$op shift()}";
1165         }
1166         $subr{'++'} = $subr{'+'};
1167         $subr{'--'} = $subr{'-'};
1168
1169       This finishes implementation of a primitive symbolic calculator in 50
1170       lines of Perl code.  Since the numeric values of subexpressions are not
1171       cached, the calculator is very slow.
1172
1173       Here is the answer for the exercise: In the case of str(), we need no
1174       explicit recursion since the overloaded "."-operator will fall back to
1175       an existing overloaded operator "".  Overloaded arithmetic operators do
1176       not fall back to numeric conversion if "fallback" is not explicitly
1177       requested.  Thus without an explicit recursion num() would convert
1178       "['+', $a, $b]" to "$a + $b", which would just rebuild the argument of
1179       num().
1180
1181       If you wonder why defaults for conversion are different for str() and
1182       num(), note how easy it was to write the symbolic calculator.  This
1183       simplicity is due to an appropriate choice of defaults.  One extra
1184       note: due to the explicit recursion num() is more fragile than sym():
1185       we need to explicitly check for the type of $a and $b.  If components
1186       $a and $b happen to be of some related type, this may lead to problems.
1187
1188   Really Symbolic Calculator
1189       One may wonder why we call the above calculator symbolic.  The reason
1190       is that the actual calculation of the value of expression is postponed
1191       until the value is used.
1192
1193       To see it in action, add a method
1194
1195         sub STORE {
1196           my $obj = shift;
1197           $#$obj = 1;
1198           @$obj->[0,1] = ('=', shift);
1199         }
1200
1201       to the package "symbolic".  After this change one can do
1202
1203         my $a = symbolic->new(3);
1204         my $b = symbolic->new(4);
1205         my $c = sqrt($a**2 + $b**2);
1206
1207       and the numeric value of $c becomes 5.  However, after calling
1208
1209         $a->STORE(12);  $b->STORE(5);
1210
1211       the numeric value of $c becomes 13.  There is no doubt now that the
1212       module symbolic provides a symbolic calculator indeed.
1213
1214       To hide the rough edges under the hood, provide a tie()d interface to
1215       the package "symbolic".  Add methods
1216
1217         sub TIESCALAR { my $pack = shift; $pack->new(@_) }
1218         sub FETCH { shift }
1219         sub nop {  }          # Around a bug
1220
1221       (the bug, fixed in Perl 5.14, is described in "BUGS").  One can use
1222       this new interface as
1223
1224         tie $a, 'symbolic', 3;
1225         tie $b, 'symbolic', 4;
1226         $a->nop;  $b->nop;    # Around a bug
1227
1228         my $c = sqrt($a**2 + $b**2);
1229
1230       Now numeric value of $c is 5.  After "$a = 12; $b = 5" the numeric
1231       value of $c becomes 13.  To insulate the user of the module add a
1232       method
1233
1234         sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
1235
1236       Now
1237
1238         my ($a, $b);
1239         symbolic->vars($a, $b);
1240         my $c = sqrt($a**2 + $b**2);
1241
1242         $a = 3; $b = 4;
1243         printf "c5  %s=%f\n", $c, $c;
1244
1245         $a = 12; $b = 5;
1246         printf "c13  %s=%f\n", $c, $c;
1247
1248       shows that the numeric value of $c follows changes to the values of $a
1249       and $b.
1250

AUTHOR

1252       Ilya Zakharevich <ilya@math.mps.ohio-state.edu>.
1253

SEE ALSO

1255       The "overloading" pragma can be used to enable or disable overloaded
1256       operations within a lexical scope - see overloading.
1257

DIAGNOSTICS

1259       When Perl is run with the -Do switch or its equivalent, overloading
1260       induces diagnostic messages.
1261
1262       Using the "m" command of Perl debugger (see perldebug) one can deduce
1263       which operations are overloaded (and which ancestor triggers this
1264       overloading).  Say, if "eq" is overloaded, then the method "(eq" is
1265       shown by debugger.  The method "()" corresponds to the "fallback" key
1266       (in fact a presence of this method shows that this package has
1267       overloading enabled, and it is what is used by the "Overloaded"
1268       function of module "overload").
1269
1270       The module might issue the following warnings:
1271
1272       Odd number of arguments for overload::constant
1273           (W) The call to overload::constant contained an odd number of
1274           arguments.  The arguments should come in pairs.
1275
1276       '%s' is not an overloadable type
1277           (W) You tried to overload a constant type the overload package is
1278           unaware of.
1279
1280       '%s' is not a code reference
1281           (W) The second (fourth, sixth, ...) argument of overload::constant
1282           needs to be a code reference.  Either an anonymous subroutine, or a
1283           reference to a subroutine.
1284
1285       overload arg '%s' is invalid
1286           (W) "use overload" was passed an argument it did not recognize.
1287           Did you mistype an operator?
1288

BUGS AND PITFALLS

1290       ·   No warning is issued for invalid "use overload" keys.  Such errors
1291           are not always obvious:
1292
1293                   use overload "+0" => sub { ...; },   # should be "0+"
1294                       "not" => sub { ...; };           # should be "!"
1295
1296           (Bug #74098)
1297
1298       ·   A pitfall when fallback is TRUE and Perl resorts to a built-in
1299           implementation of an operator is that some operators have more than
1300           one semantic, for example "|":
1301
1302                   use overload '0+' => sub { $_[0]->{n}; },
1303                       fallback => 1;
1304                   my $x = bless { n => 4 }, "main";
1305                   my $y = bless { n => 8 }, "main";
1306                   print $x | $y, "\n";
1307
1308           You might expect this to output "12".  In fact, it prints "<": the
1309           ASCII result of treating "|" as a bitwise string operator - that
1310           is, the result of treating the operands as the strings "4" and "8"
1311           rather than numbers.  The fact that numify ("0+") is implemented
1312           but stringify ("") isn't makes no difference since the latter is
1313           simply autogenerated from the former.
1314
1315           The only way to change this is to provide your own subroutine for
1316           '|'.
1317
1318       ·   Magic autogeneration increases the potential for inadvertently
1319           creating self-referential structures.  Currently Perl will not free
1320           self-referential structures until cycles are explicitly broken.
1321           For example,
1322
1323               use overload '+' => 'add';
1324               sub add { bless [ \$_[0], \$_[1] ] };
1325
1326           is asking for trouble, since
1327
1328               $obj += $y;
1329
1330           will effectively become
1331
1332               $obj = add($obj, $y, undef);
1333
1334           with the same result as
1335
1336               $obj = [\$obj, \$foo];
1337
1338           Even if no explicit assignment-variants of operators are present in
1339           the script, they may be generated by the optimizer.  For example,
1340
1341               "obj = $obj\n"
1342
1343           may be optimized to
1344
1345               my $tmp = 'obj = ' . $obj;  $tmp .= "\n";
1346
1347       ·   Because it is used for overloading, the per-package hash %OVERLOAD
1348           now has a special meaning in Perl.  The symbol table is filled with
1349           names looking like line-noise.
1350
1351       ·   For the purpose of inheritance every overloaded package behaves as
1352           if "fallback" is present (possibly undefined).  This may create
1353           interesting effects if some package is not overloaded, but inherits
1354           from two overloaded packages.
1355
1356       ·   Before Perl 5.14, the relation between overloading and tie()ing was
1357           broken.  Overloading was triggered or not based on the previous
1358           class of the tie()d variable.
1359
1360           This happened because the presence of overloading was checked too
1361           early, before any tie()d access was attempted.  If the class of the
1362           value FETCH()ed from the tied variable does not change, a simple
1363           workaround for code that is to run on older Perl versions is to
1364           access the value (via "() = $foo" or some such) immediately after
1365           tie()ing, so that after this call the previous class coincides with
1366           the current one.
1367
1368       ·   Barewords are not covered by overloaded string constants.
1369
1370
1371
1372perl v5.16.3                      2013-03-04                     overload(3pm)
Impressum