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   Declaration of overloaded functions
31       The compilation directive
32
33           package Number;
34           use overload
35               "+" => \&add,
36               "*=" => "muas";
37
38       declares function Number::add() for addition, and method muas() in the
39       "class" "Number" (or one of its base classes) for the assignment form
40       "*=" of multiplication.
41
42       Arguments of this directive come in (key, value) pairs.  Legal values
43       are values legal inside a "&{ ... }" call, so the name of a subroutine,
44       a reference to a subroutine, or an anonymous subroutine will all work.
45       Note that values specified as strings are interpreted as methods, not
46       subroutines.  Legal keys are listed below.
47
48       The subroutine "add" will be called to execute "$a+$b" if $a is a
49       reference to an object blessed into the package "Number", or if $a is
50       not an object from a package with defined mathemagic addition, but $b
51       is a reference to a "Number".  It can also be called in other
52       situations, like "$a+=7", or "$a++".  See "MAGIC AUTOGENERATION".
53       (Mathemagical methods refer to methods triggered by an overloaded
54       mathematical operator.)
55
56       Since overloading respects inheritance via the @ISA hierarchy, the
57       above declaration would also trigger overloading of "+" and "*=" in all
58       the packages which inherit from "Number".
59
60   Calling Conventions for Binary Operations
61       The functions specified in the "use overload ..." directive are called
62       with three (in one particular case with four, see "Last Resort")
63       arguments.  If the corresponding operation is binary, then the first
64       two arguments are the two arguments of the operation.  However, due to
65       general object calling conventions, the first argument should always be
66       an object in the package, so in the situation of "7+$a", the order of
67       the arguments is interchanged.  It probably does not matter when
68       implementing the addition method, but whether the arguments are
69       reversed is vital to the subtraction method.  The method can query this
70       information by examining the third argument, which can take three
71       different values:
72
73       FALSE  the order of arguments is as in the current operation.
74
75       TRUE   the arguments are reversed.
76
77       "undef"
78              the current operation is an assignment variant (as in "$a+=7"),
79              but the usual function is called instead.  This additional
80              information can be used to generate some optimizations.  Compare
81              "Calling Conventions for Mutators".
82
83   Calling Conventions for Unary Operations
84       Unary operation are considered binary operations with the second
85       argument being "undef".  Thus the functions that overloads "{"++"}" is
86       called with arguments "($a,undef,'')" when $a++ is executed.
87
88   Calling Conventions for Mutators
89       Two types of mutators have different calling conventions:
90
91       "++" and "--"
92           The routines which implement these operators are expected to
93           actually mutate their arguments.  So, assuming that $obj is a
94           reference to a number,
95
96             sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
97
98           is an appropriate implementation of overloaded "++".  Note that
99
100             sub incr { ++$ {$_[0]} ; shift }
101
102           is OK if used with preincrement and with postincrement. (In the
103           case of postincrement a copying will be performed, see "Copy
104           Constructor".)
105
106       "x=" and other assignment versions
107           There is nothing special about these methods.  They may change the
108           value of their arguments, and may leave it as is.  The result is
109           going to be assigned to the value in the left-hand-side if
110           different from this value.
111
112           This allows for the same method to be used as overloaded "+=" and
113           "+".  Note that this is allowed, but not recommended, since by the
114           semantic of "Fallback" Perl will call the method for "+" anyway, if
115           "+=" is not overloaded.
116
117       Warning.  Due to the presence of assignment versions of operations,
118       routines which may be called in assignment context may create self-
119       referential structures.  Currently Perl will not free self-referential
120       structures until cycles are "explicitly" broken.  You may get problems
121       when traversing your structures too.
122
123       Say,
124
125         use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
126
127       is asking for trouble, since for code "$obj += $foo" the subroutine is
128       called as "$obj = add($obj, $foo, undef)", or "$obj = [\$obj, \$foo]".
129       If using such a subroutine is an important optimization, one can
130       overload "+=" explicitly by a non-"optimized" version, or switch to
131       non-optimized version if "not defined $_[2]" (see "Calling Conventions
132       for Binary Operations").
133
134       Even if no explicit assignment-variants of operators are present in the
135       script, they may be generated by the optimizer.  Say, ",$obj," or ',' .
136       $obj . ',' may be both optimized to
137
138         my $tmp = ',' . $obj;    $tmp .= ',';
139
140   Overloadable Operations
141       The following symbols can be specified in "use overload" directive:
142
143       ·    Arithmetic operations
144
145                "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
146                "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
147
148            For these operations a substituted non-assignment variant can be
149            called if the assignment variant is not available.  Methods for
150            operations "+", "-", "+=", and "-=" can be called to automatically
151            generate increment and decrement methods.  The operation "-" can
152            be used to autogenerate missing methods for unary minus or "abs".
153
154            See "MAGIC AUTOGENERATION", "Calling Conventions for Mutators" and
155            "Calling Conventions for Binary Operations") for details of these
156            substitutions.
157
158       ·    Comparison operations
159
160                "<",  "<=", ">",  ">=", "==", "!=", "<=>",
161                "lt", "le", "gt", "ge", "eq", "ne", "cmp",
162
163            If the corresponding "spaceship" variant is available, it can be
164            used to substitute for the missing operation.  During "sort"ing
165            arrays, "cmp" is used to compare values subject to "use overload".
166
167       ·    Bit operations
168
169                "&", "&=", "^", "^=", "|", "|=", "neg", "!", "~",
170
171            "neg" stands for unary minus.  If the method for "neg" is not
172            specified, it can be autogenerated using the method for
173            subtraction. If the method for "!" is not specified, it can be
174            autogenerated using the methods for "bool", or "", or "0+".
175
176            The same remarks in "Arithmetic operations" about assignment-
177            variants and autogeneration apply for bit operations "&", "^", and
178            "|" as well.
179
180       ·    Increment and decrement
181
182                "++", "--",
183
184            If undefined, addition and subtraction methods can be used
185            instead.  These operations are called both in prefix and postfix
186            form.
187
188       ·    Transcendental functions
189
190                "atan2", "cos", "sin", "exp", "abs", "log", "sqrt", "int"
191
192            If "abs" is unavailable, it can be autogenerated using methods for
193            "<" or "<=>" combined with either unary minus or subtraction.
194
195            Note that traditionally the Perl function int rounds to 0, thus
196            for floating-point-like types one should follow the same semantic.
197            If "int" is unavailable, it can be autogenerated using the
198            overloading of "0+".
199
200       ·    Boolean, string, numeric and regexp conversions
201
202                'bool', '""', '0+', 'qr'
203
204            If one or two of these operations are not overloaded, the
205            remaining ones can be used instead.  "bool" is used in the flow
206            control operators (like "while") and for the ternary "?:"
207            operation; "qr" is used for the RHS of "=~" and when an object is
208            interpolated into a regexp.
209
210            "bool", "", and "0+" can return any arbitrary Perl value.  If the
211            corresponding operation for this value is overloaded too, that
212            operation will be called again with this value. "qr" must return a
213            compiled regexp, or a ref to a compiled regexp (such as "qr//"
214            returns), and any further overloading on the return value will be
215            ignored.
216
217            As a special case if the overload returns the object itself then
218            it will be used directly. An overloaded conversion returning the
219            object is probably a bug, because you're likely to get something
220            that looks like "YourPackage=HASH(0x8172b34)".
221
222       ·    Iteration
223
224                "<>"
225
226            If not overloaded, the argument will be converted to a filehandle
227            or glob (which may require a stringification).  The same
228            overloading happens both for the read-filehandle syntax "<$var>"
229            and globbing syntax "<${var}>".
230
231            BUGS Even in list context, the iterator is currently called only
232            once and with scalar context.
233
234       ·    File tests
235
236                "-X"
237
238            This overload is used for all the filetest operators ("-f", "-x"
239            and so on: see "-X" in perlfunc for the full list). Even though
240            these are unary operators, the method will be called with a second
241            argument which is a single letter indicating which test was
242            performed. Note that the overload key is the literal string "-X":
243            you can't provide separate overloads for the different tests.
244
245            Calling an overloaded filetest operator does not affect the stat
246            value associated with the special filehandle "_". It still refers
247            to the result of the last "stat", "lstat" or unoverloaded
248            filetest.
249
250            If not overloaded, these operators will fall back to the default
251            behaviour even without "fallback => 1". This means that if the
252            object is a blessed glob or blessed IO ref it will be treated as a
253            filehandle, otherwise string overloading will be invoked and the
254            result treated as a filename.
255
256            This overload was introduced in perl 5.12.
257
258       ·    Matching
259
260            The key "~~" allows you to override the smart matching logic used
261            by the "~~" operator and the switch construct ("given"/"when").
262            See "switch" in perlsyn and feature.
263
264            Unusually, overloading of the smart match operator does not
265            automatically take precedence over normal smart match behaviour.
266            In particular, in the following code:
267
268                package Foo;
269                use overload '~~' => 'match';
270
271                my $obj =  Foo->new();
272                $obj ~~ [ 1,2,3 ];
273
274            the smart match does not invoke the method call like this:
275
276                $obj->match([1,2,3],0);
277
278            rather, the smart match distributive rule takes precedence, so
279            $obj is smart matched against each array element in turn until a
280            match is found, so you may see between one and three of these
281            calls instead:
282
283                $obj->match(1,0);
284                $obj->match(2,0);
285                $obj->match(3,0);
286
287            Consult the match table in  "Smart matching in detail" in perlsyn
288            for details of when overloading is invoked.
289
290       ·    Dereferencing
291
292                '${}', '@{}', '%{}', '&{}', '*{}'.
293
294            If not overloaded, the argument will be dereferenced as is, thus
295            should be of correct type.  These functions should return a
296            reference of correct type, or another object with overloaded
297            dereferencing.
298
299            As a special case if the overload returns the object itself then
300            it will be used directly (provided it is the correct type).
301
302            The dereference operators must be specified explicitly they will
303            not be passed to "nomethod".
304
305       ·    Special
306
307                "nomethod", "fallback", "=".
308
309            see "SPECIAL SYMBOLS FOR "use overload"".
310
311       See "Fallback" for an explanation of when a missing method can be
312       autogenerated.
313
314       A computer-readable form of the above table is available in the hash
315       %overload::ops, with values being space-separated lists of names:
316
317        with_assign      => '+ - * / % ** << >> x .',
318        assign           => '+= -= *= /= %= **= <<= >>= x= .=',
319        num_comparison   => '< <= > >= == !=',
320        '3way_comparison'=> '<=> cmp',
321        str_comparison   => 'lt le gt ge eq ne',
322        binary           => '& &= | |= ^ ^=',
323        unary            => 'neg ! ~',
324        mutators         => '++ --',
325        func             => 'atan2 cos sin exp abs log sqrt',
326        conversion       => 'bool "" 0+ qr',
327        iterators        => '<>',
328        filetest         => '-X',
329        dereferencing    => '${} @{} %{} &{} *{}',
330        matching         => '~~',
331        special          => 'nomethod fallback ='
332
333   Inheritance and overloading
334       Inheritance interacts with overloading in two ways.
335
336       Strings as values of "use overload" directive
337           If "value" in
338
339             use overload key => value;
340
341           is a string, it is interpreted as a method name.
342
343       Overloading of an operation is inherited by derived classes
344           Any class derived from an overloaded class is also overloaded.  The
345           set of overloaded methods is the union of overloaded methods of all
346           the ancestors. If some method is overloaded in several ancestor,
347           then which description will be used is decided by the usual
348           inheritance rules:
349
350           If "A" inherits from "B" and "C" (in this order), "B" overloads "+"
351           with "\&D::plus_sub", and "C" overloads "+" by "plus_meth", then
352           the subroutine "D::plus_sub" will be called to implement operation
353           "+" for an object in package "A".
354
355       Note that since the value of the "fallback" key is not a subroutine,
356       its inheritance is not governed by the above rules.  In the current
357       implementation, the value of "fallback" in the first overloaded
358       ancestor is used, but this is accidental and subject to change.
359

SPECIAL SYMBOLS FOR "use overload"

361       Three keys are recognized by Perl that are not covered by the above
362       description.
363
364   Last Resort
365       "nomethod" should be followed by a reference to a function of four
366       parameters.  If defined, it is called when the overloading mechanism
367       cannot find a method for some operation.  The first three arguments of
368       this function coincide with the arguments for the corresponding method
369       if it were found, the fourth argument is the symbol corresponding to
370       the missing method.  If several methods are tried, the last one is
371       used.  Say, "1-$a" can be equivalent to
372
373               &nomethodMethod($a,1,1,"-")
374
375       if the pair "nomethod" => "nomethodMethod" was specified in the "use
376       overload" directive.
377
378       The "nomethod" mechanism is not used for the dereference operators (
379       ${} @{} %{} &{} *{} ).
380
381       If some operation cannot be resolved, and there is no function assigned
382       to "nomethod", then an exception will be raised via die()-- unless
383       "fallback" was specified as a key in "use overload" directive.
384
385   Fallback
386       The key "fallback" governs what to do if a method for a particular
387       operation is not found.  Three different cases are possible depending
388       on the value of "fallback":
389
390       ·               "undef"
391
392                       Perl tries to use a substituted method (see "MAGIC
393                       AUTOGENERATION").  If this fails, it then tries to
394                       calls "nomethod" value; if missing, an exception will
395                       be raised.
396
397       ·               TRUE
398
399                       The same as for the "undef" value, but no exception is
400                       raised.  Instead, it silently reverts to what it would
401                       have done were there no "use overload" present.
402
403       ·               defined, but FALSE
404
405                       No autogeneration is tried.  Perl tries to call
406                       "nomethod" value, and if this is missing, raises an
407                       exception.
408
409       Note. "fallback" inheritance via @ISA is not carved in stone yet, see
410       "Inheritance and overloading".
411
412   Copy Constructor
413       The value for "=" is a reference to a function with three arguments,
414       i.e., it looks like the other values in "use overload". However, it
415       does not overload the Perl assignment operator. This would go against
416       Camel hair.
417
418       This operation is called in the situations when a mutator is applied to
419       a reference that shares its object with some other reference, such as
420
421               $a=$b;
422               ++$a;
423
424       To make this change $a and not change $b, a copy of $$a is made, and $a
425       is assigned a reference to this new object.  This operation is done
426       during execution of the "++$a", and not during the assignment, (so
427       before the increment $$a coincides with $$b).  This is only done if
428       "++" is expressed via a method for '++' or '+=' (or "nomethod").  Note
429       that if this operation is expressed via '+' a nonmutator, i.e., as in
430
431               $a=$b;
432               $a=$a+1;
433
434       then $a does not reference a new copy of $$a, since $$a does not appear
435       as lvalue when the above code is executed.
436
437       If the copy constructor is required during the execution of some
438       mutator, but a method for '=' was not specified, it can be
439       autogenerated as a string copy if the object is a plain scalar or a
440       simple assignment if it is not.
441
442       Example
443            The actually executed code for
444
445                    $a=$b;
446                    Something else which does not modify $a or $b....
447                    ++$a;
448
449            may be
450
451                    $a=$b;
452                    Something else which does not modify $a or $b....
453                    $a = $a->clone(undef,"");
454                    $a->incr(undef,"");
455
456            if $b was mathemagical, and '++' was overloaded with "\&incr", '='
457            was overloaded with "\&clone".
458
459       Same behaviour is triggered by "$b = $a++", which is consider a synonym
460       for "$b = $a; ++$a".
461

MAGIC AUTOGENERATION

463       If a method for an operation is not found, and the value for
464       "fallback" is TRUE or undefined, Perl tries to autogenerate a
465       substitute method for the missing operation based on the defined
466       operations.  Autogenerated method substitutions are possible for the
467       following operations:
468
469       Assignment forms of arithmetic operations
470                       "$a+=$b" can use the method for "+" if the method for
471                       "+=" is not defined.
472
473       Conversion operations
474                       String, numeric, boolean and regexp conversions are
475                       calculated in terms of one another if not all of them
476                       are defined.
477
478       Increment and decrement
479                       The "++$a" operation can be expressed in terms of
480                       "$a+=1" or "$a+1", and "$a--" in terms of "$a-=1" and
481                       "$a-1".
482
483       "abs($a)"       can be expressed in terms of "$a<0" and "-$a" (or
484                       "0-$a").
485
486       Unary minus     can be expressed in terms of subtraction.
487
488       Negation        "!" and "not" can be expressed in terms of boolean
489                       conversion, or string or numerical conversion.
490
491       Concatenation   can be expressed in terms of string conversion.
492
493       Comparison operations
494                       can be expressed in terms of its "spaceship"
495                       counterpart: either "<=>" or "cmp":
496
497                           <, >, <=, >=, ==, !=        in terms of <=>
498                           lt, gt, le, ge, eq, ne      in terms of cmp
499
500       Iterator
501                           <>                          in terms of builtin operations
502
503       Dereferencing
504                           ${} @{} %{} &{} *{}         in terms of builtin operations
505
506       Copy operator   can be expressed in terms of an assignment to the
507                       dereferenced value, if this value is a scalar and not a
508                       reference, or simply a reference assignment otherwise.
509

Minimal set of overloaded operations

511       Since some operations can be automatically generated from others, there
512       is a minimal set of operations that need to be overloaded in order to
513       have the complete set of overloaded operations at one's disposal.  Of
514       course, the autogenerated operations may not do exactly what the user
515       expects. See "MAGIC AUTOGENERATION" above. The minimal set is:
516
517           + - * / % ** << >> x
518           <=> cmp
519           & | ^ ~
520           atan2 cos sin exp log sqrt int
521
522       Additionally, you need to define at least one of string, boolean or
523       numeric conversions because any one can be used to emulate the others.
524       The string conversion can also be used to emulate concatenation.
525

Losing overloading

527       The restriction for the comparison operation is that even if, for
528       example, `"cmp"' should return a blessed reference, the autogenerated
529       `"lt"' function will produce only a standard logical value based on the
530       numerical value of the result of `"cmp"'.  In particular, a working
531       numeric conversion is needed in this case (possibly expressed in terms
532       of other conversions).
533
534       Similarly, ".="  and "x=" operators lose their mathemagical properties
535       if the string conversion substitution is applied.
536
537       When you chop() a mathemagical object it is promoted to a string and
538       its mathemagical properties are lost.  The same can happen with other
539       operations as well.
540

Run-time Overloading

542       Since all "use" directives are executed at compile-time, the only way
543       to change overloading during run-time is to
544
545           eval 'use overload "+" => \&addmethod';
546
547       You can also use
548
549           eval 'no overload "+", "--", "<="';
550
551       though the use of these constructs during run-time is questionable.
552

Public functions

554       Package "overload.pm" provides the following public functions:
555
556       overload::StrVal(arg)
557            Gives string value of "arg" as in absence of stringify
558            overloading. If you are using this to get the address of a
559            reference (useful for checking if two references point to the same
560            thing) then you may be better off using "Scalar::Util::refaddr()",
561            which is faster.
562
563       overload::Overloaded(arg)
564            Returns true if "arg" is subject to overloading of some
565            operations.
566
567       overload::Method(obj,op)
568            Returns "undef" or a reference to the method that implements "op".
569

Overloading constants

571       For some applications, the Perl parser mangles constants too much.  It
572       is possible to hook into this process via "overload::constant()" and
573       "overload::remove_constant()" functions.
574
575       These functions take a hash as an argument.  The recognized keys of
576       this hash are:
577
578       integer to overload integer constants,
579
580       float   to overload floating point constants,
581
582       binary  to overload octal and hexadecimal constants,
583
584       q       to overload "q"-quoted strings, constant pieces of "qq"- and
585               "qx"-quoted strings and here-documents,
586
587       qr      to overload constant pieces of regular expressions.
588
589       The corresponding values are references to functions which take three
590       arguments: the first one is the initial string form of the constant,
591       the second one is how Perl interprets this constant, the third one is
592       how the constant is used.  Note that the initial string form does not
593       contain string delimiters, and has backslashes in backslash-delimiter
594       combinations stripped (thus the value of delimiter is not relevant for
595       processing of this string).  The return value of this function is how
596       this constant is going to be interpreted by Perl.  The third argument
597       is undefined unless for overloaded "q"- and "qr"- constants, it is "q"
598       in single-quote context (comes from strings, regular expressions, and
599       single-quote HERE documents), it is "tr" for arguments of "tr"/"y"
600       operators, it is "s" for right-hand side of "s"-operator, and it is
601       "qq" otherwise.
602
603       Since an expression "ab$cd,," is just a shortcut for 'ab' . $cd . ',,',
604       it is expected that overloaded constant strings are equipped with
605       reasonable overloaded catenation operator, otherwise absurd results
606       will result.  Similarly, negative numbers are considered as negations
607       of positive constants.
608
609       Note that it is probably meaningless to call the functions
610       overload::constant() and overload::remove_constant() from anywhere but
611       import() and unimport() methods.  From these methods they may be called
612       as
613
614               sub import {
615                 shift;
616                 return unless @_;
617                 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
618                 overload::constant integer => sub {Math::BigInt->new(shift)};
619               }
620

IMPLEMENTATION

622       What follows is subject to change RSN.
623
624       The table of methods for all operations is cached in magic for the
625       symbol table hash for the package.  The cache is invalidated during
626       processing of "use overload", "no overload", new function definitions,
627       and changes in @ISA. However, this invalidation remains unprocessed
628       until the next "bless"ing into the package. Hence if you want to change
629       overloading structure dynamically, you'll need an additional (fake)
630       "bless"ing to update the table.
631
632       (Every SVish thing has a magic queue, and magic is an entry in that
633       queue.  This is how a single variable may participate in multiple forms
634       of magic simultaneously.  For instance, environment variables regularly
635       have two forms at once: their %ENV magic and their taint magic.
636       However, the magic which implements overloading is applied to the
637       stashes, which are rarely used directly, thus should not slow down
638       Perl.)
639
640       If an object belongs to a package using overload, it carries a special
641       flag.  Thus the only speed penalty during arithmetic operations without
642       overloading is the checking of this flag.
643
644       In fact, if "use overload" is not present, there is almost no overhead
645       for overloadable operations, so most programs should not suffer
646       measurable performance penalties.  A considerable effort was made to
647       minimize the overhead when overload is used in some package, but the
648       arguments in question do not belong to packages using overload.  When
649       in doubt, test your speed with "use overload" and without it.  So far
650       there have been no reports of substantial speed degradation if Perl is
651       compiled with optimization turned on.
652
653       There is no size penalty for data if overload is not used. The only
654       size penalty if overload is used in some package is that all the
655       packages acquire a magic during the next "bless"ing into the package.
656       This magic is three-words-long for packages without overloading, and
657       carries the cache table if the package is overloaded.
658
659       Copying ("$a=$b") is shallow; however, a one-level-deep copying is
660       carried out before any operation that can imply an assignment to the
661       object $a (or $b) refers to, like "$a++".  You can override this
662       behavior by defining your own copy constructor (see "Copy
663       Constructor").
664
665       It is expected that arguments to methods that are not explicitly
666       supposed to be changed are constant (but this is not enforced).
667

Metaphor clash

669       One may wonder why the semantic of overloaded "=" is so counter
670       intuitive.  If it looks counter intuitive to you, you are subject to a
671       metaphor clash.
672
673       Here is a Perl object metaphor:
674
675         object is a reference to blessed data
676
677       and an arithmetic metaphor:
678
679         object is a thing by itself.
680
681       The main problem of overloading "=" is the fact that these metaphors
682       imply different actions on the assignment "$a = $b" if $a and $b are
683       objects.  Perl-think implies that $a becomes a reference to whatever $b
684       was referencing.  Arithmetic-think implies that the value of "object"
685       $a is changed to become the value of the object $b, preserving the fact
686       that $a and $b are separate entities.
687
688       The difference is not relevant in the absence of mutators.  After a
689       Perl-way assignment an operation which mutates the data referenced by
690       $a would change the data referenced by $b too.  Effectively, after "$a
691       = $b" values of $a and $b become indistinguishable.
692
693       On the other hand, anyone who has used algebraic notation knows the
694       expressive power of the arithmetic metaphor.  Overloading works hard to
695       enable this metaphor while preserving the Perlian way as far as
696       possible.  Since it is not possible to freely mix two contradicting
697       metaphors, overloading allows the arithmetic way to write things as far
698       as all the mutators are called via overloaded access only.  The way it
699       is done is described in "Copy Constructor".
700
701       If some mutator methods are directly applied to the overloaded values,
702       one may need to explicitly unlink other values which references the
703       same value:
704
705           $a = Data->new(23);
706           ...
707           $b = $a;            # $b is "linked" to $a
708           ...
709           $a = $a->clone;     # Unlink $b from $a
710           $a->increment_by(4);
711
712       Note that overloaded access makes this transparent:
713
714           $a = Data->new(23);
715           $b = $a;            # $b is "linked" to $a
716           $a += 4;            # would unlink $b automagically
717
718       However, it would not make
719
720           $a = Data->new(23);
721           $a = 4;             # Now $a is a plain 4, not 'Data'
722
723       preserve "objectness" of $a.  But Perl has a way to make assignments to
724       an object do whatever you want.  It is just not the overload, but
725       tie()ing interface (see "tie" in perlfunc).  Adding a FETCH() method
726       which returns the object itself, and STORE() method which changes the
727       value of the object, one can reproduce the arithmetic metaphor in its
728       completeness, at least for variables which were tie()d from the start.
729
730       (Note that a workaround for a bug may be needed, see "BUGS".)
731

Cookbook

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

AUTHOR

1191       Ilya Zakharevich <ilya@math.mps.ohio-state.edu>.
1192

SEE ALSO

1194       The overloading pragma can be used to enable or disable overloaded
1195       operations within a lexical scope.
1196

DIAGNOSTICS

1198       When Perl is run with the -Do switch or its equivalent, overloading
1199       induces diagnostic messages.
1200
1201       Using the "m" command of Perl debugger (see perldebug) one can deduce
1202       which operations are overloaded (and which ancestor triggers this
1203       overloading). Say, if "eq" is overloaded, then the method "(eq" is
1204       shown by debugger. The method "()" corresponds to the "fallback" key
1205       (in fact a presence of this method shows that this package has
1206       overloading enabled, and it is what is used by the "Overloaded"
1207       function of module "overload").
1208
1209       The module might issue the following warnings:
1210
1211       Odd number of arguments for overload::constant
1212           (W) The call to overload::constant contained an odd number of
1213           arguments.  The arguments should come in pairs.
1214
1215       `%s' is not an overloadable type
1216           (W) You tried to overload a constant type the overload package is
1217           unaware of.
1218
1219       `%s' is not a code reference
1220           (W) The second (fourth, sixth, ...) argument of overload::constant
1221           needs to be a code reference. Either an anonymous subroutine, or a
1222           reference to a subroutine.
1223

BUGS

1225       Because it is used for overloading, the per-package hash %OVERLOAD now
1226       has a special meaning in Perl. The symbol table is filled with names
1227       looking like line-noise.
1228
1229       For the purpose of inheritance every overloaded package behaves as if
1230       "fallback" is present (possibly undefined). This may create interesting
1231       effects if some package is not overloaded, but inherits from two
1232       overloaded packages.
1233
1234       Relation between overloading and tie()ing is broken.  Overloading is
1235       triggered or not basing on the previous class of tie()d value.
1236
1237       This happens because the presence of overloading is checked too early,
1238       before any tie()d access is attempted.  If the FETCH()ed class of the
1239       tie()d value does not change, a simple workaround is to access the
1240       value immediately after tie()ing, so that after this call the previous
1241       class coincides with the current one.
1242
1243       Needed: a way to fix this without a speed penalty.
1244
1245       Barewords are not covered by overloaded string constants.
1246
1247       This document is confusing.  There are grammos and misleading language
1248       used in places.  It would seem a total rewrite is needed.
1249
1250
1251
1252perl v5.12.4                      2011-06-07                     overload(3pm)
Impressum