1overload(3pm) Perl Programmers Reference Guide overload(3pm)
2
3
4
6 overload - Package for overloading Perl operations
7
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
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 and numeric conversion
201
202 'bool', '""', '0+',
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. These functions can return any arbitrary Perl value.
208 If the corresponding operation for this value is overloaded too,
209 that operation will be called again with this value.
210
211 As a special case if the overload returns the object itself then
212 it will be used directly. An overloaded conversion returning the
213 object is probably a bug, because you're likely to get something
214 that looks like "YourPackage=HASH(0x8172b34)".
215
216 · Iteration
217
218 "<>"
219
220 If not overloaded, the argument will be converted to a filehandle
221 or glob (which may require a stringification). The same
222 overloading happens both for the read-filehandle syntax "<$var>"
223 and globbing syntax "<${var}>".
224
225 BUGS Even in list context, the iterator is currently called only
226 once and with scalar context.
227
228 · Matching
229
230 The key "~~" allows you to override the smart matching logic used
231 by the "~~" operator and the switch construct ("given"/"when").
232 See "switch" in perlsyn and feature.
233
234 Unusually, overloading of the smart match operator does not
235 automatically take precedence over normal smart match behaviour.
236 In particular, in the following code:
237
238 package Foo;
239 use overload '~~' => 'match';
240
241 my $obj = Foo->new();
242 $obj ~~ [ 1,2,3 ];
243
244 the smart match does not invoke the method call like this:
245
246 $obj->match([1,2,3],0);
247
248 rather, the smart match distributive rule takes precedence, so
249 $obj is smart matched against each array element in turn until a
250 match is found, so you may see between one and three of these
251 calls instead:
252
253 $obj->match(1,0);
254 $obj->match(2,0);
255 $obj->match(3,0);
256
257 Consult the match table in "Smart matching in detail" in perlsyn
258 for details of when overloading is invoked.
259
260 · Dereferencing
261
262 '${}', '@{}', '%{}', '&{}', '*{}'.
263
264 If not overloaded, the argument will be dereferenced as is, thus
265 should be of correct type. These functions should return a
266 reference of correct type, or another object with overloaded
267 dereferencing.
268
269 As a special case if the overload returns the object itself then
270 it will be used directly (provided it is the correct type).
271
272 The dereference operators must be specified explicitly they will
273 not be passed to "nomethod".
274
275 · Special
276
277 "nomethod", "fallback", "=".
278
279 see "SPECIAL SYMBOLS FOR "use overload"".
280
281 See "Fallback" for an explanation of when a missing method can be
282 autogenerated.
283
284 A computer-readable form of the above table is available in the hash
285 %overload::ops, with values being space-separated lists of names:
286
287 with_assign => '+ - * / % ** << >> x .',
288 assign => '+= -= *= /= %= **= <<= >>= x= .=',
289 num_comparison => '< <= > >= == !=',
290 '3way_comparison'=> '<=> cmp',
291 str_comparison => 'lt le gt ge eq ne',
292 binary => '& &= | |= ^ ^=',
293 unary => 'neg ! ~',
294 mutators => '++ --',
295 func => 'atan2 cos sin exp abs log sqrt',
296 conversion => 'bool "" 0+',
297 iterators => '<>',
298 dereferencing => '${} @{} %{} &{} *{}',
299 matching => '~~',
300 special => 'nomethod fallback ='
301
302 Inheritance and overloading
303 Inheritance interacts with overloading in two ways.
304
305 Strings as values of "use overload" directive
306 If "value" in
307
308 use overload key => value;
309
310 is a string, it is interpreted as a method name.
311
312 Overloading of an operation is inherited by derived classes
313 Any class derived from an overloaded class is also overloaded. The
314 set of overloaded methods is the union of overloaded methods of all
315 the ancestors. If some method is overloaded in several ancestor,
316 then which description will be used is decided by the usual
317 inheritance rules:
318
319 If "A" inherits from "B" and "C" (in this order), "B" overloads "+"
320 with "\&D::plus_sub", and "C" overloads "+" by "plus_meth", then
321 the subroutine "D::plus_sub" will be called to implement operation
322 "+" for an object in package "A".
323
324 Note that since the value of the "fallback" key is not a subroutine,
325 its inheritance is not governed by the above rules. In the current
326 implementation, the value of "fallback" in the first overloaded
327 ancestor is used, but this is accidental and subject to change.
328
330 Three keys are recognized by Perl that are not covered by the above
331 description.
332
333 Last Resort
334 "nomethod" should be followed by a reference to a function of four
335 parameters. If defined, it is called when the overloading mechanism
336 cannot find a method for some operation. The first three arguments of
337 this function coincide with the arguments for the corresponding method
338 if it were found, the fourth argument is the symbol corresponding to
339 the missing method. If several methods are tried, the last one is
340 used. Say, "1-$a" can be equivalent to
341
342 &nomethodMethod($a,1,1,"-")
343
344 if the pair "nomethod" => "nomethodMethod" was specified in the "use
345 overload" directive.
346
347 The "nomethod" mechanism is not used for the dereference operators (
348 ${} @{} %{} &{} *{} ).
349
350 If some operation cannot be resolved, and there is no function assigned
351 to "nomethod", then an exception will be raised via die()-- unless
352 "fallback" was specified as a key in "use overload" directive.
353
354 Fallback
355 The key "fallback" governs what to do if a method for a particular
356 operation is not found. Three different cases are possible depending
357 on the value of "fallback":
358
359 · "undef"
360
361 Perl tries to use a substituted method (see "MAGIC
362 AUTOGENERATION"). If this fails, it then tries to
363 calls "nomethod" value; if missing, an exception will
364 be raised.
365
366 · TRUE
367
368 The same as for the "undef" value, but no exception is
369 raised. Instead, it silently reverts to what it would
370 have done were there no "use overload" present.
371
372 · defined, but FALSE
373
374 No autogeneration is tried. Perl tries to call
375 "nomethod" value, and if this is missing, raises an
376 exception.
377
378 Note. "fallback" inheritance via @ISA is not carved in stone yet, see
379 "Inheritance and overloading".
380
381 Copy Constructor
382 The value for "=" is a reference to a function with three arguments,
383 i.e., it looks like the other values in "use overload". However, it
384 does not overload the Perl assignment operator. This would go against
385 Camel hair.
386
387 This operation is called in the situations when a mutator is applied to
388 a reference that shares its object with some other reference, such as
389
390 $a=$b;
391 ++$a;
392
393 To make this change $a and not change $b, a copy of $$a is made, and $a
394 is assigned a reference to this new object. This operation is done
395 during execution of the "++$a", and not during the assignment, (so
396 before the increment $$a coincides with $$b). This is only done if
397 "++" is expressed via a method for '++' or '+=' (or "nomethod"). Note
398 that if this operation is expressed via '+' a nonmutator, i.e., as in
399
400 $a=$b;
401 $a=$a+1;
402
403 then $a does not reference a new copy of $$a, since $$a does not appear
404 as lvalue when the above code is executed.
405
406 If the copy constructor is required during the execution of some
407 mutator, but a method for '=' was not specified, it can be
408 autogenerated as a string copy if the object is a plain scalar or a
409 simple assignment if it is not.
410
411 Example
412 The actually executed code for
413
414 $a=$b;
415 Something else which does not modify $a or $b....
416 ++$a;
417
418 may be
419
420 $a=$b;
421 Something else which does not modify $a or $b....
422 $a = $a->clone(undef,"");
423 $a->incr(undef,"");
424
425 if $b was mathemagical, and '++' was overloaded with "\&incr", '='
426 was overloaded with "\&clone".
427
428 Same behaviour is triggered by "$b = $a++", which is consider a synonym
429 for "$b = $a; ++$a".
430
432 If a method for an operation is not found, and the value for
433 "fallback" is TRUE or undefined, Perl tries to autogenerate a
434 substitute method for the missing operation based on the defined
435 operations. Autogenerated method substitutions are possible for the
436 following operations:
437
438 Assignment forms of arithmetic operations
439 "$a+=$b" can use the method for "+" if the method for
440 "+=" is not defined.
441
442 Conversion operations
443 String, numeric, and boolean conversion are calculated
444 in terms of one another if not all of them are defined.
445
446 Increment and decrement
447 The "++$a" operation can be expressed in terms of
448 "$a+=1" or "$a+1", and "$a--" in terms of "$a-=1" and
449 "$a-1".
450
451 "abs($a)" can be expressed in terms of "$a<0" and "-$a" (or
452 "0-$a").
453
454 Unary minus can be expressed in terms of subtraction.
455
456 Negation "!" and "not" can be expressed in terms of boolean
457 conversion, or string or numerical conversion.
458
459 Concatenation can be expressed in terms of string conversion.
460
461 Comparison operations
462 can be expressed in terms of its "spaceship"
463 counterpart: either "<=>" or "cmp":
464
465 <, >, <=, >=, ==, != in terms of <=>
466 lt, gt, le, ge, eq, ne in terms of cmp
467
468 Iterator
469 <> in terms of builtin operations
470
471 Dereferencing
472 ${} @{} %{} &{} *{} in terms of builtin operations
473
474 Copy operator can be expressed in terms of an assignment to the
475 dereferenced value, if this value is a scalar and not a
476 reference, or simply a reference assignment otherwise.
477
479 Since some operations can be automatically generated from others, there
480 is a minimal set of operations that need to be overloaded in order to
481 have the complete set of overloaded operations at one's disposal. Of
482 course, the autogenerated operations may not do exactly what the user
483 expects. See "MAGIC AUTOGENERATION" above. The minimal set is:
484
485 + - * / % ** << >> x
486 <=> cmp
487 & | ^ ~
488 atan2 cos sin exp log sqrt int
489
490 Additionally, you need to define at least one of string, boolean or
491 numeric conversions because any one can be used to emulate the others.
492 The string conversion can also be used to emulate concatenation.
493
495 The restriction for the comparison operation is that even if, for
496 example, `"cmp"' should return a blessed reference, the autogenerated
497 `"lt"' function will produce only a standard logical value based on the
498 numerical value of the result of `"cmp"'. In particular, a working
499 numeric conversion is needed in this case (possibly expressed in terms
500 of other conversions).
501
502 Similarly, ".=" and "x=" operators lose their mathemagical properties
503 if the string conversion substitution is applied.
504
505 When you chop() a mathemagical object it is promoted to a string and
506 its mathemagical properties are lost. The same can happen with other
507 operations as well.
508
510 Since all "use" directives are executed at compile-time, the only way
511 to change overloading during run-time is to
512
513 eval 'use overload "+" => \&addmethod';
514
515 You can also use
516
517 eval 'no overload "+", "--", "<="';
518
519 though the use of these constructs during run-time is questionable.
520
522 Package "overload.pm" provides the following public functions:
523
524 overload::StrVal(arg)
525 Gives string value of "arg" as in absence of stringify
526 overloading. If you are using this to get the address of a
527 reference (useful for checking if two references point to the same
528 thing) then you may be better off using "Scalar::Util::refaddr()",
529 which is faster.
530
531 overload::Overloaded(arg)
532 Returns true if "arg" is subject to overloading of some
533 operations.
534
535 overload::Method(obj,op)
536 Returns "undef" or a reference to the method that implements "op".
537
539 For some applications, the Perl parser mangles constants too much. It
540 is possible to hook into this process via "overload::constant()" and
541 "overload::remove_constant()" functions.
542
543 These functions take a hash as an argument. The recognized keys of
544 this hash are:
545
546 integer to overload integer constants,
547
548 float to overload floating point constants,
549
550 binary to overload octal and hexadecimal constants,
551
552 q to overload "q"-quoted strings, constant pieces of "qq"- and
553 "qx"-quoted strings and here-documents,
554
555 qr to overload constant pieces of regular expressions.
556
557 The corresponding values are references to functions which take three
558 arguments: the first one is the initial string form of the constant,
559 the second one is how Perl interprets this constant, the third one is
560 how the constant is used. Note that the initial string form does not
561 contain string delimiters, and has backslashes in backslash-delimiter
562 combinations stripped (thus the value of delimiter is not relevant for
563 processing of this string). The return value of this function is how
564 this constant is going to be interpreted by Perl. The third argument
565 is undefined unless for overloaded "q"- and "qr"- constants, it is "q"
566 in single-quote context (comes from strings, regular expressions, and
567 single-quote HERE documents), it is "tr" for arguments of "tr"/"y"
568 operators, it is "s" for right-hand side of "s"-operator, and it is
569 "qq" otherwise.
570
571 Since an expression "ab$cd,," is just a shortcut for 'ab' . $cd . ',,',
572 it is expected that overloaded constant strings are equipped with
573 reasonable overloaded catenation operator, otherwise absurd results
574 will result. Similarly, negative numbers are considered as negations
575 of positive constants.
576
577 Note that it is probably meaningless to call the functions
578 overload::constant() and overload::remove_constant() from anywhere but
579 import() and unimport() methods. From these methods they may be called
580 as
581
582 sub import {
583 shift;
584 return unless @_;
585 die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
586 overload::constant integer => sub {Math::BigInt->new(shift)};
587 }
588
590 What follows is subject to change RSN.
591
592 The table of methods for all operations is cached in magic for the
593 symbol table hash for the package. The cache is invalidated during
594 processing of "use overload", "no overload", new function definitions,
595 and changes in @ISA. However, this invalidation remains unprocessed
596 until the next "bless"ing into the package. Hence if you want to change
597 overloading structure dynamically, you'll need an additional (fake)
598 "bless"ing to update the table.
599
600 (Every SVish thing has a magic queue, and magic is an entry in that
601 queue. This is how a single variable may participate in multiple forms
602 of magic simultaneously. For instance, environment variables regularly
603 have two forms at once: their %ENV magic and their taint magic.
604 However, the magic which implements overloading is applied to the
605 stashes, which are rarely used directly, thus should not slow down
606 Perl.)
607
608 If an object belongs to a package using overload, it carries a special
609 flag. Thus the only speed penalty during arithmetic operations without
610 overloading is the checking of this flag.
611
612 In fact, if "use overload" is not present, there is almost no overhead
613 for overloadable operations, so most programs should not suffer
614 measurable performance penalties. A considerable effort was made to
615 minimize the overhead when overload is used in some package, but the
616 arguments in question do not belong to packages using overload. When
617 in doubt, test your speed with "use overload" and without it. So far
618 there have been no reports of substantial speed degradation if Perl is
619 compiled with optimization turned on.
620
621 There is no size penalty for data if overload is not used. The only
622 size penalty if overload is used in some package is that all the
623 packages acquire a magic during the next "bless"ing into the package.
624 This magic is three-words-long for packages without overloading, and
625 carries the cache table if the package is overloaded.
626
627 Copying ("$a=$b") is shallow; however, a one-level-deep copying is
628 carried out before any operation that can imply an assignment to the
629 object $a (or $b) refers to, like "$a++". You can override this
630 behavior by defining your own copy constructor (see "Copy
631 Constructor").
632
633 It is expected that arguments to methods that are not explicitly
634 supposed to be changed are constant (but this is not enforced).
635
637 One may wonder why the semantic of overloaded "=" is so counter
638 intuitive. If it looks counter intuitive to you, you are subject to a
639 metaphor clash.
640
641 Here is a Perl object metaphor:
642
643 object is a reference to blessed data
644
645 and an arithmetic metaphor:
646
647 object is a thing by itself.
648
649 The main problem of overloading "=" is the fact that these metaphors
650 imply different actions on the assignment "$a = $b" if $a and $b are
651 objects. Perl-think implies that $a becomes a reference to whatever $b
652 was referencing. Arithmetic-think implies that the value of "object"
653 $a is changed to become the value of the object $b, preserving the fact
654 that $a and $b are separate entities.
655
656 The difference is not relevant in the absence of mutators. After a
657 Perl-way assignment an operation which mutates the data referenced by
658 $a would change the data referenced by $b too. Effectively, after "$a
659 = $b" values of $a and $b become indistinguishable.
660
661 On the other hand, anyone who has used algebraic notation knows the
662 expressive power of the arithmetic metaphor. Overloading works hard to
663 enable this metaphor while preserving the Perlian way as far as
664 possible. Since it is not possible to freely mix two contradicting
665 metaphors, overloading allows the arithmetic way to write things as far
666 as all the mutators are called via overloaded access only. The way it
667 is done is described in "Copy Constructor".
668
669 If some mutator methods are directly applied to the overloaded values,
670 one may need to explicitly unlink other values which references the
671 same value:
672
673 $a = Data->new(23);
674 ...
675 $b = $a; # $b is "linked" to $a
676 ...
677 $a = $a->clone; # Unlink $b from $a
678 $a->increment_by(4);
679
680 Note that overloaded access makes this transparent:
681
682 $a = Data->new(23);
683 $b = $a; # $b is "linked" to $a
684 $a += 4; # would unlink $b automagically
685
686 However, it would not make
687
688 $a = Data->new(23);
689 $a = 4; # Now $a is a plain 4, not 'Data'
690
691 preserve "objectness" of $a. But Perl has a way to make assignments to
692 an object do whatever you want. It is just not the overload, but
693 tie()ing interface (see "tie" in perlfunc). Adding a FETCH() method
694 which returns the object itself, and STORE() method which changes the
695 value of the object, one can reproduce the arithmetic metaphor in its
696 completeness, at least for variables which were tie()d from the start.
697
698 (Note that a workaround for a bug may be needed, see "BUGS".)
699
701 Please add examples to what follows!
702
703 Two-face scalars
704 Put this in two_face.pm in your Perl library directory:
705
706 package two_face; # Scalars with separate string and
707 # numeric values.
708 sub new { my $p = shift; bless [@_], $p }
709 use overload '""' => \&str, '0+' => \&num, fallback => 1;
710 sub num {shift->[1]}
711 sub str {shift->[0]}
712
713 Use it as follows:
714
715 require two_face;
716 my $seven = two_face->new("vii", 7);
717 printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
718 print "seven contains `i'\n" if $seven =~ /i/;
719
720 (The second line creates a scalar which has both a string value, and a
721 numeric value.) This prints:
722
723 seven=vii, seven=7, eight=8
724 seven contains `i'
725
726 Two-face references
727 Suppose you want to create an object which is accessible as both an
728 array reference and a hash reference.
729
730 package two_refs;
731 use overload '%{}' => \&gethash, '@{}' => sub { $ {shift()} };
732 sub new {
733 my $p = shift;
734 bless \ [@_], $p;
735 }
736 sub gethash {
737 my %h;
738 my $self = shift;
739 tie %h, ref $self, $self;
740 \%h;
741 }
742
743 sub TIEHASH { my $p = shift; bless \ shift, $p }
744 my %fields;
745 my $i = 0;
746 $fields{$_} = $i++ foreach qw{zero one two three};
747 sub STORE {
748 my $self = ${shift()};
749 my $key = $fields{shift()};
750 defined $key or die "Out of band access";
751 $$self->[$key] = shift;
752 }
753 sub FETCH {
754 my $self = ${shift()};
755 my $key = $fields{shift()};
756 defined $key or die "Out of band access";
757 $$self->[$key];
758 }
759
760 Now one can access an object using both the array and hash syntax:
761
762 my $bar = two_refs->new(3,4,5,6);
763 $bar->[2] = 11;
764 $bar->{two} == 11 or die 'bad hash fetch';
765
766 Note several important features of this example. First of all, the
767 actual type of $bar is a scalar reference, and we do not overload the
768 scalar dereference. Thus we can get the actual non-overloaded contents
769 of $bar by just using $$bar (what we do in functions which overload
770 dereference). Similarly, the object returned by the TIEHASH() method
771 is a scalar reference.
772
773 Second, we create a new tied hash each time the hash syntax is used.
774 This allows us not to worry about a possibility of a reference loop,
775 which would lead to a memory leak.
776
777 Both these problems can be cured. Say, if we want to overload hash
778 dereference on a reference to an object which is implemented as a hash
779 itself, the only problem one has to circumvent is how to access this
780 actual hash (as opposed to the virtual hash exhibited by the overloaded
781 dereference operator). Here is one possible fetching routine:
782
783 sub access_hash {
784 my ($self, $key) = (shift, shift);
785 my $class = ref $self;
786 bless $self, 'overload::dummy'; # Disable overloading of %{}
787 my $out = $self->{$key};
788 bless $self, $class; # Restore overloading
789 $out;
790 }
791
792 To remove creation of the tied hash on each access, one may an extra
793 level of indirection which allows a non-circular structure of
794 references:
795
796 package two_refs1;
797 use overload '%{}' => sub { ${shift()}->[1] },
798 '@{}' => sub { ${shift()}->[0] };
799 sub new {
800 my $p = shift;
801 my $a = [@_];
802 my %h;
803 tie %h, $p, $a;
804 bless \ [$a, \%h], $p;
805 }
806 sub gethash {
807 my %h;
808 my $self = shift;
809 tie %h, ref $self, $self;
810 \%h;
811 }
812
813 sub TIEHASH { my $p = shift; bless \ shift, $p }
814 my %fields;
815 my $i = 0;
816 $fields{$_} = $i++ foreach qw{zero one two three};
817 sub STORE {
818 my $a = ${shift()};
819 my $key = $fields{shift()};
820 defined $key or die "Out of band access";
821 $a->[$key] = shift;
822 }
823 sub FETCH {
824 my $a = ${shift()};
825 my $key = $fields{shift()};
826 defined $key or die "Out of band access";
827 $a->[$key];
828 }
829
830 Now if $baz is overloaded like this, then $baz is a reference to a
831 reference to the intermediate array, which keeps a reference to an
832 actual array, and the access hash. The tie()ing object for the access
833 hash is a reference to a reference to the actual array, so
834
835 · There are no loops of references.
836
837 · Both "objects" which are blessed into the class "two_refs1" are
838 references to a reference to an array, thus references to a scalar.
839 Thus the accessor expression "$$foo->[$ind]" involves no overloaded
840 operations.
841
842 Symbolic calculator
843 Put this in symbolic.pm in your Perl library directory:
844
845 package symbolic; # Primitive symbolic calculator
846 use overload nomethod => \&wrap;
847
848 sub new { shift; bless ['n', @_] }
849 sub wrap {
850 my ($obj, $other, $inv, $meth) = @_;
851 ($obj, $other) = ($other, $obj) if $inv;
852 bless [$meth, $obj, $other];
853 }
854
855 This module is very unusual as overloaded modules go: it does not
856 provide any usual overloaded operators, instead it provides the Last
857 Resort operator "nomethod". In this example the corresponding
858 subroutine returns an object which encapsulates operations done over
859 the objects: "symbolic->new(3)" contains "['n', 3]", "2 +
860 symbolic->new(3)" contains "['+', 2, ['n', 3]]".
861
862 Here is an example of the script which "calculates" the side of
863 circumscribed octagon using the above package:
864
865 require symbolic;
866 my $iter = 1; # 2**($iter+2) = 8
867 my $side = symbolic->new(1);
868 my $cnt = $iter;
869
870 while ($cnt--) {
871 $side = (sqrt(1 + $side**2) - 1)/$side;
872 }
873 print "OK\n";
874
875 The value of $side is
876
877 ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
878 undef], 1], ['n', 1]]
879
880 Note that while we obtained this value using a nice little script,
881 there is no simple way to use this value. In fact this value may be
882 inspected in debugger (see perldebug), but only if "bareStringify"
883 Option is set, and not via "p" command.
884
885 If one attempts to print this value, then the overloaded operator ""
886 will be called, which will call "nomethod" operator. The result of
887 this operator will be stringified again, but this result is again of
888 type "symbolic", which will lead to an infinite loop.
889
890 Add a pretty-printer method to the module symbolic.pm:
891
892 sub pretty {
893 my ($meth, $a, $b) = @{+shift};
894 $a = 'u' unless defined $a;
895 $b = 'u' unless defined $b;
896 $a = $a->pretty if ref $a;
897 $b = $b->pretty if ref $b;
898 "[$meth $a $b]";
899 }
900
901 Now one can finish the script by
902
903 print "side = ", $side->pretty, "\n";
904
905 The method "pretty" is doing object-to-string conversion, so it is
906 natural to overload the operator "" using this method. However, inside
907 such a method it is not necessary to pretty-print the components $a and
908 $b of an object. In the above subroutine "[$meth $a $b]" is a
909 catenation of some strings and components $a and $b. If these
910 components use overloading, the catenation operator will look for an
911 overloaded operator "."; if not present, it will look for an overloaded
912 operator "". Thus it is enough to use
913
914 use overload nomethod => \&wrap, '""' => \&str;
915 sub str {
916 my ($meth, $a, $b) = @{+shift};
917 $a = 'u' unless defined $a;
918 $b = 'u' unless defined $b;
919 "[$meth $a $b]";
920 }
921
922 Now one can change the last line of the script to
923
924 print "side = $side\n";
925
926 which outputs
927
928 side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
929
930 and one can inspect the value in debugger using all the possible
931 methods.
932
933 Something is still amiss: consider the loop variable $cnt of the
934 script. It was a number, not an object. We cannot make this value of
935 type "symbolic", since then the loop will not terminate.
936
937 Indeed, to terminate the cycle, the $cnt should become false. However,
938 the operator "bool" for checking falsity is overloaded (this time via
939 overloaded ""), and returns a long string, thus any object of type
940 "symbolic" is true. To overcome this, we need a way to compare an
941 object to 0. In fact, it is easier to write a numeric conversion
942 routine.
943
944 Here is the text of symbolic.pm with such a routine added (and slightly
945 modified str()):
946
947 package symbolic; # Primitive symbolic calculator
948 use overload
949 nomethod => \&wrap, '""' => \&str, '0+' => \#
950
951 sub new { shift; bless ['n', @_] }
952 sub wrap {
953 my ($obj, $other, $inv, $meth) = @_;
954 ($obj, $other) = ($other, $obj) if $inv;
955 bless [$meth, $obj, $other];
956 }
957 sub str {
958 my ($meth, $a, $b) = @{+shift};
959 $a = 'u' unless defined $a;
960 if (defined $b) {
961 "[$meth $a $b]";
962 } else {
963 "[$meth $a]";
964 }
965 }
966 my %subr = ( n => sub {$_[0]},
967 sqrt => sub {sqrt $_[0]},
968 '-' => sub {shift() - shift()},
969 '+' => sub {shift() + shift()},
970 '/' => sub {shift() / shift()},
971 '*' => sub {shift() * shift()},
972 '**' => sub {shift() ** shift()},
973 );
974 sub num {
975 my ($meth, $a, $b) = @{+shift};
976 my $subr = $subr{$meth}
977 or die "Do not know how to ($meth) in symbolic";
978 $a = $a->num if ref $a eq __PACKAGE__;
979 $b = $b->num if ref $b eq __PACKAGE__;
980 $subr->($a,$b);
981 }
982
983 All the work of numeric conversion is done in %subr and num(). Of
984 course, %subr is not complete, it contains only operators used in the
985 example below. Here is the extra-credit question: why do we need an
986 explicit recursion in num()? (Answer is at the end of this section.)
987
988 Use this module like this:
989
990 require symbolic;
991 my $iter = symbolic->new(2); # 16-gon
992 my $side = symbolic->new(1);
993 my $cnt = $iter;
994
995 while ($cnt) {
996 $cnt = $cnt - 1; # Mutator `--' not implemented
997 $side = (sqrt(1 + $side**2) - 1)/$side;
998 }
999 printf "%s=%f\n", $side, $side;
1000 printf "pi=%f\n", $side*(2**($iter+2));
1001
1002 It prints (without so many line breaks)
1003
1004 [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1]
1005 [n 1]] 2]]] 1]
1006 [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1007 pi=3.182598
1008
1009 The above module is very primitive. It does not implement mutator
1010 methods ("++", "-=" and so on), does not do deep copying (not required
1011 without mutators!), and implements only those arithmetic operations
1012 which are used in the example.
1013
1014 To implement most arithmetic operations is easy; one should just use
1015 the tables of operations, and change the code which fills %subr to
1016
1017 my %subr = ( 'n' => sub {$_[0]} );
1018 foreach my $op (split " ", $overload::ops{with_assign}) {
1019 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1020 }
1021 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1022 foreach my $op (split " ", "@overload::ops{ @bins }") {
1023 $subr{$op} = eval "sub {shift() $op shift()}";
1024 }
1025 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1026 print "defining `$op'\n";
1027 $subr{$op} = eval "sub {$op shift()}";
1028 }
1029
1030 Due to "Calling Conventions for Mutators", we do not need anything
1031 special to make "+=" and friends work, except filling "+=" entry of
1032 %subr, and defining a copy constructor (needed since Perl has no way to
1033 know that the implementation of '+=' does not mutate the argument,
1034 compare "Copy Constructor").
1035
1036 To implement a copy constructor, add "'=' => \&cpy" to "use overload"
1037 line, and code (this code assumes that mutators change things one level
1038 deep only, so recursive copying is not needed):
1039
1040 sub cpy {
1041 my $self = shift;
1042 bless [@$self], ref $self;
1043 }
1044
1045 To make "++" and "--" work, we need to implement actual mutators,
1046 either directly, or in "nomethod". We continue to do things inside
1047 "nomethod", thus add
1048
1049 if ($meth eq '++' or $meth eq '--') {
1050 @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1051 return $obj;
1052 }
1053
1054 after the first line of wrap(). This is not a most effective
1055 implementation, one may consider
1056
1057 sub inc { $_[0] = bless ['++', shift, 1]; }
1058
1059 instead.
1060
1061 As a final remark, note that one can fill %subr by
1062
1063 my %subr = ( 'n' => sub {$_[0]} );
1064 foreach my $op (split " ", $overload::ops{with_assign}) {
1065 $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1066 }
1067 my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1068 foreach my $op (split " ", "@overload::ops{ @bins }") {
1069 $subr{$op} = eval "sub {shift() $op shift()}";
1070 }
1071 foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1072 $subr{$op} = eval "sub {$op shift()}";
1073 }
1074 $subr{'++'} = $subr{'+'};
1075 $subr{'--'} = $subr{'-'};
1076
1077 This finishes implementation of a primitive symbolic calculator in 50
1078 lines of Perl code. Since the numeric values of subexpressions are not
1079 cached, the calculator is very slow.
1080
1081 Here is the answer for the exercise: In the case of str(), we need no
1082 explicit recursion since the overloaded "."-operator will fall back to
1083 an existing overloaded operator "". Overloaded arithmetic operators do
1084 not fall back to numeric conversion if "fallback" is not explicitly
1085 requested. Thus without an explicit recursion num() would convert
1086 "['+', $a, $b]" to "$a + $b", which would just rebuild the argument of
1087 num().
1088
1089 If you wonder why defaults for conversion are different for str() and
1090 num(), note how easy it was to write the symbolic calculator. This
1091 simplicity is due to an appropriate choice of defaults. One extra
1092 note: due to the explicit recursion num() is more fragile than sym():
1093 we need to explicitly check for the type of $a and $b. If components
1094 $a and $b happen to be of some related type, this may lead to problems.
1095
1096 Really symbolic calculator
1097 One may wonder why we call the above calculator symbolic. The reason
1098 is that the actual calculation of the value of expression is postponed
1099 until the value is used.
1100
1101 To see it in action, add a method
1102
1103 sub STORE {
1104 my $obj = shift;
1105 $#$obj = 1;
1106 @$obj->[0,1] = ('=', shift);
1107 }
1108
1109 to the package "symbolic". After this change one can do
1110
1111 my $a = symbolic->new(3);
1112 my $b = symbolic->new(4);
1113 my $c = sqrt($a**2 + $b**2);
1114
1115 and the numeric value of $c becomes 5. However, after calling
1116
1117 $a->STORE(12); $b->STORE(5);
1118
1119 the numeric value of $c becomes 13. There is no doubt now that the
1120 module symbolic provides a symbolic calculator indeed.
1121
1122 To hide the rough edges under the hood, provide a tie()d interface to
1123 the package "symbolic" (compare with "Metaphor clash"). Add methods
1124
1125 sub TIESCALAR { my $pack = shift; $pack->new(@_) }
1126 sub FETCH { shift }
1127 sub nop { } # Around a bug
1128
1129 (the bug is described in "BUGS"). One can use this new interface as
1130
1131 tie $a, 'symbolic', 3;
1132 tie $b, 'symbolic', 4;
1133 $a->nop; $b->nop; # Around a bug
1134
1135 my $c = sqrt($a**2 + $b**2);
1136
1137 Now numeric value of $c is 5. After "$a = 12; $b = 5" the numeric
1138 value of $c becomes 13. To insulate the user of the module add a
1139 method
1140
1141 sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
1142
1143 Now
1144
1145 my ($a, $b);
1146 symbolic->vars($a, $b);
1147 my $c = sqrt($a**2 + $b**2);
1148
1149 $a = 3; $b = 4;
1150 printf "c5 %s=%f\n", $c, $c;
1151
1152 $a = 12; $b = 5;
1153 printf "c13 %s=%f\n", $c, $c;
1154
1155 shows that the numeric value of $c follows changes to the values of $a
1156 and $b.
1157
1159 Ilya Zakharevich <ilya@math.mps.ohio-state.edu>.
1160
1162 The overloading pragma can be used to enable or disable overloaded
1163 operations within a lexical scope.
1164
1166 When Perl is run with the -Do switch or its equivalent, overloading
1167 induces diagnostic messages.
1168
1169 Using the "m" command of Perl debugger (see perldebug) one can deduce
1170 which operations are overloaded (and which ancestor triggers this
1171 overloading). Say, if "eq" is overloaded, then the method "(eq" is
1172 shown by debugger. The method "()" corresponds to the "fallback" key
1173 (in fact a presence of this method shows that this package has
1174 overloading enabled, and it is what is used by the "Overloaded"
1175 function of module "overload").
1176
1177 The module might issue the following warnings:
1178
1179 Odd number of arguments for overload::constant
1180 (W) The call to overload::constant contained an odd number of
1181 arguments. The arguments should come in pairs.
1182
1183 `%s' is not an overloadable type
1184 (W) You tried to overload a constant type the overload package is
1185 unaware of.
1186
1187 `%s' is not a code reference
1188 (W) The second (fourth, sixth, ...) argument of overload::constant
1189 needs to be a code reference. Either an anonymous subroutine, or a
1190 reference to a subroutine.
1191
1193 Because it is used for overloading, the per-package hash %OVERLOAD now
1194 has a special meaning in Perl. The symbol table is filled with names
1195 looking like line-noise.
1196
1197 For the purpose of inheritance every overloaded package behaves as if
1198 "fallback" is present (possibly undefined). This may create interesting
1199 effects if some package is not overloaded, but inherits from two
1200 overloaded packages.
1201
1202 Relation between overloading and tie()ing is broken. Overloading is
1203 triggered or not basing on the previous class of tie()d value.
1204
1205 This happens because the presence of overloading is checked too early,
1206 before any tie()d access is attempted. If the FETCH()ed class of the
1207 tie()d value does not change, a simple workaround is to access the
1208 value immediately after tie()ing, so that after this call the previous
1209 class coincides with the current one.
1210
1211 Needed: a way to fix this without a speed penalty.
1212
1213 Barewords are not covered by overloaded string constants.
1214
1215 This document is confusing. There are grammos and misleading language
1216 used in places. It would seem a total rewrite is needed.
1217
1218
1219
1220perl v5.10.1 2009-08-22 overload(3pm)