Debian Codegraph @

upstream/opensuse-tumbleweed/man3/overload.3pm

raw
1 .\" -*- mode: troff; coding: utf-8 -*-
2 .\" Automatically generated by Pod::Man v6.0.2 (Pod::Simple 3.45)
3 .\"
4 .\" Standard preamble:
5 .\" ========================================================================
6 .de Sp \" Vertical space (when we can't use .PP)
7 .if t .sp .5v
8 .if n .sp
9 ..
10 .de Vb \" Begin verbatim text
11 .ft CW
12 .nf
13 .ne \\$1
14 ..
15 .de Ve \" End verbatim text
16 .ft R
17 .fi
18 ..
19 .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>.
20 .ie n \{\
21 . ds C` ""
22 . ds C' ""
23 'br\}
24 .el\{\
25 . ds C`
26 . ds C'
27 'br\}
28 .\"
29 .\" Escape single quotes in literal strings from groff's Unicode transform.
30 .ie \n(.g .ds Aq \(aq
31 .el .ds Aq '
32 .\"
33 .\" If the F register is >0, we'll generate index entries on stderr for
34 .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index
35 .\" entries marked with X<> in POD. Of course, you'll have to process the
36 .\" output yourself in some meaningful fashion.
37 .\"
38 .\" Avoid warning from groff about undefined register 'F'.
39 .de IX
40 ..
41 .nr rF 0
42 .if \n(.g .if rF .nr rF 1
43 .if (\n(rF:(\n(.g==0)) \{\
44 . if \nF \{\
45 . de IX
46 . tm Index:\\$1\t\\n%\t"\\$2"
47 ..
48 . if !\nF==2 \{\
49 . nr % 0
50 . nr F 2
51 . \}
52 . \}
53 .\}
54 .rr rF
55 .\"
56 .\" Required to disable full justification in groff 1.23.0.
57 .if n .ds AD l
58 .\" ========================================================================
59 .\"
60 .IX Title "overload 3pm"
61 .TH overload 3pm 2026-03-09 "perl v5.42.1" "Perl Programmers Reference Guide"
62 .\" For nroff, turn off justification. Always turn off hyphenation; it makes
63 .\" way too many mistakes in technical documents.
64 .if n .ad l
65 .nh
66 .SH NAME
67 overload \- Package for overloading Perl operations
68 .SH SYNOPSIS
69 .IX Header "SYNOPSIS"
70 .Vb 1
71 \& package SomeThing;
72 \&
73 \& use overload
74 \& \*(Aq+\*(Aq => \e&myadd,
75 \& \*(Aq\-\*(Aq => \e&mysub;
76 \& # etc
77 \& ...
78 \&
79 \& package main;
80 \& $a = SomeThing\->new( 57 );
81 \& $b = 5 + $a;
82 \& ...
83 \& if (overload::Overloaded $b) {...}
84 \& ...
85 \& $strval = overload::StrVal $b;
86 .Ve
87 .SH DESCRIPTION
88 .IX Header "DESCRIPTION"
89 This pragma allows overloading of Perl\*(Aqs operators for a class.
90 To overload built\-in functions, see "Overriding Built\-in Functions" in perlsub instead.
91 .SS Fundamentals
92 .IX Subsection "Fundamentals"
93 \fIDeclaration\fR
94 .IX Subsection "Declaration"
95 .PP
96 Arguments of the \f(CW\*(C`use overload\*(C'\fR directive are (key, value) pairs.
97 For the full set of legal keys, see "Overloadable Operations" below.
98 .PP
99 Operator implementations (the values) can be subroutines,
100 references to subroutines, or anonymous subroutines
101 \&\- in other words, anything legal inside a \f(CW\*(C`&{ ... }\*(C'\fR call.
102 Values specified as strings are interpreted as method names.
103 Thus
104 .PP
105 .Vb 5
106 \& package Number;
107 \& use overload
108 \& "\-" => "minus",
109 \& "*=" => \e&muas,
110 \& \*(Aq""\*(Aq => sub { ...; };
111 .Ve
112 .PP
113 declares that subtraction is to be implemented by method \f(CWminus()\fR
114 in the class \f(CW\*(C`Number\*(C'\fR (or one of its base classes),
115 and that the function \f(CWNumber::muas()\fR is to be used for the
116 assignment form of multiplication, \f(CW\*(C`*=\*(C'\fR.
117 It also defines an anonymous subroutine to implement stringification:
118 this is called whenever an object blessed into the package \f(CW\*(C`Number\*(C'\fR
119 is used in a string context (this subroutine might, for example,
120 return the number as a Roman numeral).
121 .PP
122 \fICalling Conventions and Magic Autogeneration\fR
123 .IX Subsection "Calling Conventions and Magic Autogeneration"
124 .PP
125 The following sample implementation of \f(CWminus()\fR (which assumes
126 that \f(CW\*(C`Number\*(C'\fR objects are simply blessed references to scalars)
127 illustrates the calling conventions:
128 .PP
129 .Vb 8
130 \& package Number;
131 \& sub minus {
132 \& my ($self, $other, $swap) = @_;
133 \& my $result = $$self \- $other; # *
134 \& $result = \-$result if $swap;
135 \& ref $result ? $result : bless \e$result;
136 \& }
137 \& # * may recurse once \- see table below
138 .Ve
139 .PP
140 Three arguments are passed to all subroutines specified in the
141 \&\f(CW\*(C`use overload\*(C'\fR directive (with exceptions \- see below, particularly
142 "nomethod").
143 .PP
144 The first of these is the operand providing the overloaded
145 operator implementation \-
146 in this case, the object whose \f(CWminus()\fR method is being called.
147 .PP
148 The second argument is the other operand, or \f(CW\*(C`undef\*(C'\fR in the
149 case of a unary operator.
150 .PP
151 The third argument is set to TRUE if (and only if) the two
152 operands have been swapped. Perl may do this to ensure that the
153 first argument (\f(CW$self\fR) is an object implementing the overloaded
154 operation, in line with general object calling conventions.
155 For example, if \f(CW$x\fR and \f(CW$y\fR are \f(CW\*(C`Number\*(C'\fRs:
156 .PP
157 .Vb 5
158 \& operation | generates a call to
159 \& ============|======================
160 \& $x \- $y | minus($x, $y, \*(Aq\*(Aq)
161 \& $x \- 7 | minus($x, 7, \*(Aq\*(Aq)
162 \& 7 \- $x | minus($x, 7, 1)
163 .Ve
164 .PP
165 Perl may also use \f(CWminus()\fR to implement other operators which
166 have not been specified in the \f(CW\*(C`use overload\*(C'\fR directive,
167 according to the rules for "Magic Autogeneration" described later.
168 For example, the \f(CW\*(C`use overload\*(C'\fR above declared no subroutine
169 for any of the operators \f(CW\*(C`\-\-\*(C'\fR, \f(CW\*(C`neg\*(C'\fR (the overload key for
170 unary minus), or \f(CW\*(C`\-=\*(C'\fR. Thus
171 .PP
172 .Vb 5
173 \& operation | generates a call to
174 \& ============|======================
175 \& \-$x | minus($x, 0, 1)
176 \& $x\-\- | minus($x, 1, undef)
177 \& $x \-= 3 | minus($x, 3, undef)
178 .Ve
179 .PP
180 Note the \f(CW\*(C`undef\*(C'\fRs:
181 where autogeneration results in the method for a standard
182 operator which does not change either of its operands, such
183 as \f(CW\*(C`\-\*(C'\fR, being used to implement an operator which changes
184 the operand ("mutators": here, \f(CW\*(C`\-\-\*(C'\fR and \f(CW\*(C`\-=\*(C'\fR),
185 Perl passes undef as the third argument.
186 This still evaluates as FALSE, consistent with the fact that
187 the operands have not been swapped, but gives the subroutine
188 a chance to alter its behaviour in these cases.
189 .PP
190 In all the above examples, \f(CWminus()\fR is required
191 only to return the result of the subtraction:
192 Perl takes care of the assignment to \f(CW$x\fR.
193 In fact, such methods should \fInot\fR modify their operands,
194 even if \f(CW\*(C`undef\*(C'\fR is passed as the third argument
195 (see "Overloadable Operations").
196 .PP
197 The same is not true of implementations of \f(CW\*(C`++\*(C'\fR and \f(CW\*(C`\-\-\*(C'\fR:
198 these are expected to modify their operand.
199 An appropriate implementation of \f(CW\*(C`\-\-\*(C'\fR might look like
200 .PP
201 .Vb 3
202 \& use overload \*(Aq\-\-\*(Aq => "decr",
203 \& # ...
204 \& sub decr { \-\-${$_[0]}; }
205 .Ve
206 .PP
207 If the "bitwise" feature is enabled (see feature), a fifth
208 TRUE argument is passed to subroutines handling \f(CW\*(C`&\*(C'\fR, \f(CW\*(C`|\*(C'\fR, \f(CW\*(C`^\*(C'\fR and \f(CW\*(C`~\*(C'\fR.
209 This indicates that the caller is expecting numeric behaviour. The fourth
210 argument will be \f(CW\*(C`undef\*(C'\fR, as that position (\f(CW$_[3]\fR) is reserved for use
211 by "nomethod".
212 .PP
213 \fIMathemagic, Mutators, and Copy Constructors\fR
214 .IX Subsection "Mathemagic, Mutators, and Copy Constructors"
215 .PP
216 The term \*(Aqmathemagic\*(Aq describes the overloaded implementation
217 of mathematical operators.
218 Mathemagical operations raise an issue.
219 Consider the code:
220 .PP
221 .Vb 2
222 \& $a = $b;
223 \& \-\-$a;
224 .Ve
225 .PP
226 If \f(CW$a\fR and \f(CW$b\fR are scalars then after these statements
227 .PP
228 .Vb 1
229 \& $a == $b \- 1
230 .Ve
231 .PP
232 An object, however, is a reference to blessed data, so if
233 \&\f(CW$a\fR and \f(CW$b\fR are objects then the assignment \f(CW\*(C`$a = $b\*(C'\fR
234 copies only the reference, leaving \f(CW$a\fR and \f(CW$b\fR referring
235 to the same object data.
236 One might therefore expect the operation \f(CW\*(C`\-\-$a\*(C'\fR to decrement
237 \&\f(CW$b\fR as well as \f(CW$a\fR.
238 However, this would not be consistent with how we expect the
239 mathematical operators to work.
240 .PP
241 Perl resolves this dilemma by transparently calling a copy
242 constructor before calling a method defined to implement
243 a mutator (\f(CW\*(C`\-\-\*(C'\fR, \f(CW\*(C`+=\*(C'\fR, and so on.).
244 In the above example, when Perl reaches the decrement
245 statement, it makes a copy of the object data in \f(CW$a\fR and
246 assigns to \f(CW$a\fR a reference to the copied data.
247 Only then does it call \f(CWdecr()\fR, which alters the copied
248 data, leaving \f(CW$b\fR unchanged.
249 Thus the object metaphor is preserved as far as possible,
250 while mathemagical operations still work according to the
251 arithmetic metaphor.
252 .PP
253 Note: the preceding paragraph describes what happens when
254 Perl autogenerates the copy constructor for an object based
255 on a scalar.
256 For other cases, see "Copy Constructor".
257 .SS "Overloadable Operations"
258 .IX Subsection "Overloadable Operations"
259 The complete list of keys that can be specified in the \f(CW\*(C`use overload\*(C'\fR
260 directive are given, separated by spaces, in the values of the
261 hash \f(CW%overload::ops\fR:
262 .PP
263 .Vb 10
264 \& with_assign => \*(Aq+ \- * / % ** << >> x .\*(Aq,
265 \& assign => \*(Aq+= \-= *= /= %= **= <<= >>= x= .=\*(Aq,
266 \& num_comparison => \*(Aq< <= > >= == !=\*(Aq,
267 \& \*(Aq3way_comparison\*(Aq => \*(Aq<=> cmp\*(Aq,
268 \& str_comparison => \*(Aqlt le gt ge eq ne\*(Aq,
269 \& binary => \*(Aq& &= | |= ^ ^= &. &.= |. |.= ^. ^.=\*(Aq,
270 \& unary => \*(Aqneg ! ~ ~.\*(Aq,
271 \& mutators => \*(Aq++ \-\-\*(Aq,
272 \& func => \*(Aqatan2 cos sin exp abs log sqrt int\*(Aq,
273 \& conversion => \*(Aqbool "" 0+ qr\*(Aq,
274 \& iterators => \*(Aq<>\*(Aq,
275 \& filetest => \*(Aq\-X\*(Aq,
276 \& dereferencing => \*(Aq${} @{} %{} &{} *{}\*(Aq,
277 \& matching => \*(Aq~~\*(Aq,
278 \& special => \*(Aqnomethod fallback =\*(Aq,
279 .Ve
280 .PP
281 Most of the overloadable operators map one\-to\-one to these keys.
282 Exceptions, including additional overloadable operations not
283 apparent from this hash, are included in the notes which follow.
284 This list is subject to growth over time.
285 .PP
286 A warning is issued if an attempt is made to register an operator not found
287 above.
288 .IP \(bu 5
289 \&\f(CW\*(C`not\*(C'\fR
290 .Sp
291 The operator \f(CW\*(C`not\*(C'\fR is not a valid key for \f(CW\*(C`use overload\*(C'\fR.
292 However, if the operator \f(CW\*(C`!\*(C'\fR is overloaded then the same
293 implementation will be used for \f(CW\*(C`not\*(C'\fR
294 (since the two operators differ only in precedence).
295 .IP \(bu 5
296 \&\f(CW\*(C`neg\*(C'\fR
297 .Sp
298 The key \f(CW\*(C`neg\*(C'\fR is used for unary minus to disambiguate it from
299 binary \f(CW\*(C`\-\*(C'\fR.
300 .IP \(bu 5
301 \&\f(CW\*(C`++\*(C'\fR, \f(CW\*(C`\-\-\*(C'\fR
302 .Sp
303 Assuming they are to behave analogously to Perl\*(Aqs \f(CW\*(C`++\*(C'\fR and \f(CW\*(C`\-\-\*(C'\fR,
304 overloaded implementations of these operators are required to
305 mutate their operands.
306 .Sp
307 No distinction is made between prefix and postfix forms of the
308 increment and decrement operators: these differ only in the
309 point at which Perl calls the associated subroutine when
310 evaluating an expression.
311 .IP \(bu 5
312 \&\fIAssignments\fR
313 .Sp
314 .Vb 2
315 \& += \-= *= /= %= **= <<= >>= x= .=
316 \& &= |= ^= &.= |.= ^.=
317 .Ve
318 .Sp
319 Simple assignment is not overloadable (the \f(CW\*(Aq=\*(Aq\fR key is used
320 for the "Copy Constructor").
321 Perl does have a way to make assignments to an object do whatever
322 you want, but this involves using \fBtie()\fR, not overload \-
323 see "tie" in perlfunc and the "COOKBOOK" examples below.
324 .Sp
325 The subroutine for the assignment variant of an operator is
326 required only to return the result of the operation.
327 It is permitted to change the value of its operand
328 (this is safe because Perl calls the copy constructor first),
329 but this is optional since Perl assigns the returned value to
330 the left\-hand operand anyway.
331 .Sp
332 An object that overloads an assignment operator does so only in
333 respect of assignments to that object.
334 In other words, Perl never calls the corresponding methods with
335 the third argument (the "swap" argument) set to TRUE.
336 For example, the operation
337 .Sp
338 .Vb 1
339 \& $a *= $b
340 .Ve
341 .Sp
342 cannot lead to \f(CW$b\fR\*(Aqs implementation of \f(CW\*(C`*=\*(C'\fR being called,
343 even if \f(CW$a\fR is a scalar.
344 (It can, however, generate a call to \f(CW$b\fR\*(Aqs method for \f(CW\*(C`*\*(C'\fR).
345 .IP \(bu 5
346 \&\fINon\-mutators with a mutator variant\fR
347 .Sp
348 .Vb 2
349 \& + \- * / % ** << >> x .
350 \& & | ^ &. |. ^.
351 .Ve
352 .Sp
353 As described above,
354 Perl may call methods for operators like \f(CW\*(C`+\*(C'\fR and \f(CW\*(C`&\*(C'\fR in the course
355 of implementing missing operations like \f(CW\*(C`++\*(C'\fR, \f(CW\*(C`+=\*(C'\fR, and \f(CW\*(C`&=\*(C'\fR.
356 While these methods may detect this usage by testing the definedness
357 of the third argument, they should in all cases avoid changing their
358 operands.
359 This is because Perl does not call the copy constructor before
360 invoking these methods.
361 .IP \(bu 5
362 \&\f(CW\*(C`int\*(C'\fR
363 .Sp
364 Traditionally, the Perl function \f(CW\*(C`int\*(C'\fR rounds to 0
365 (see "int" in perlfunc), and so for floating\-point\-like types one
366 should follow the same semantic.
367 .IP \(bu 5
368 \&\fIString, numeric, boolean, and regexp conversions\fR
369 .Sp
370 .Vb 1
371 \& "" 0+ bool
372 .Ve
373 .Sp
374 These conversions are invoked according to context as necessary.
375 For example, the subroutine for \f(CW\*(Aq""\*(Aq\fR (stringify) may be used
376 where the overloaded object is passed as an argument to \f(CW\*(C`print\*(C'\fR,
377 and that for \f(CW\*(Aqbool\*(Aq\fR where it is tested in the condition of a flow
378 control statement (like \f(CW\*(C`while\*(C'\fR) or the ternary \f(CW\*(C`?:\*(C'\fR operation.
379 .Sp
380 Of course, in contexts like, for example, \f(CW\*(C`$obj + 1\*(C'\fR, Perl will
381 invoke \f(CW$obj\fR\*(Aqs implementation of \f(CW\*(C`+\*(C'\fR rather than (in this
382 example) converting \f(CW$obj\fR to a number using the numify method
383 \&\f(CW\*(Aq0+\*(Aq\fR (an exception to this is when no method has been provided
384 for \f(CW\*(Aq+\*(Aq\fR and "fallback" is set to TRUE).
385 .Sp
386 The subroutines for \f(CW\*(Aq""\*(Aq\fR, \f(CW\*(Aq0+\*(Aq\fR, and \f(CW\*(Aqbool\*(Aq\fR can return
387 any arbitrary Perl value.
388 If the corresponding operation for this value is overloaded too,
389 the operation will be called again with this value.
390 .Sp
391 As a special case if the overload returns the object itself then it will
392 be used directly. An overloaded conversion returning the object is
393 probably a bug, because you\*(Aqre likely to get something that looks like
394 \&\f(CW\*(C`YourPackage=HASH(0x8172b34)\*(C'\fR.
395 .Sp
396 .Vb 1
397 \& qr
398 .Ve
399 .Sp
400 The subroutine for \f(CW\*(Aqqr\*(Aq\fR is used wherever the object is
401 interpolated into or used as a regexp, including when it
402 appears on the RHS of a \f(CW\*(C`=~\*(C'\fR or \f(CW\*(C`!~\*(C'\fR operator.
403 .Sp
404 \&\f(CW\*(C`qr\*(C'\fR must return a compiled regexp, or a ref to a compiled regexp
405 (such as \f(CW\*(C`qr//\*(C'\fR returns), and any further overloading on the return
406 value will be ignored.
407 .IP \(bu 5
408 \&\fIIteration\fR
409 .Sp
410 If \f(CW\*(C`<>\*(C'\fR is overloaded then the same implementation is used
411 for both the \fIread\-filehandle\fR syntax \f(CW\*(C`<$var>\*(C'\fR and
412 \&\fIglobbing\fR syntax \f(CW\*(C`<${var}>\*(C'\fR.
413 .IP \(bu 5
414 \&\fIFile tests\fR
415 .Sp
416 The key \f(CW\*(Aq\-X\*(Aq\fR is used to specify a subroutine to handle all the
417 filetest operators (\f(CW\*(C`\-f\*(C'\fR, \f(CW\*(C`\-x\*(C'\fR, and so on: see "\-X" in perlfunc for
418 the full list);
419 it is not possible to overload any filetest operator individually.
420 To distinguish them, the letter following the \*(Aq\-\*(Aq is passed as the
421 second argument (that is, in the slot that for binary operators
422 is used to pass the second operand).
423 .Sp
424 Calling an overloaded filetest operator does not affect the stat value
425 associated with the special filehandle \f(CW\*(C`_\*(C'\fR. It still refers to the
426 result of the last \f(CW\*(C`stat\*(C'\fR, \f(CW\*(C`lstat\*(C'\fR or unoverloaded filetest.
427 .Sp
428 This overload was introduced in Perl 5.12.
429 .IP \(bu 5
430 \&\fIMatching\fR
431 .Sp
432 The key \f(CW"~~"\fR allows you to override the smart matching logic used by
433 the \f(CW\*(C`~~\*(C'\fR operator and the switch construct (\f(CW\*(C`given\*(C'\fR/\f(CW\*(C`when\*(C'\fR). See
434 "Switch Statements" in perlsyn and feature.
435 .Sp
436 Unusually, the overloaded implementation of the smart match operator
437 does not get full control of the smart match behaviour.
438 In particular, in the following code:
439 .Sp
440 .Vb 2
441 \& package Foo;
442 \& use overload \*(Aq~~\*(Aq => \*(Aqmatch\*(Aq;
443 \&
444 \& my $obj = Foo\->new();
445 \& $obj ~~ [ 1,2,3 ];
446 .Ve
447 .Sp
448 the smart match does \fInot\fR invoke the method call like this:
449 .Sp
450 .Vb 1
451 \& $obj\->match([1,2,3],0);
452 .Ve
453 .Sp
454 rather, the smart match distributive rule takes precedence, so \f(CW$obj\fR is
455 smart matched against each array element in turn until a match is found,
456 so you may see between one and three of these calls instead:
457 .Sp
458 .Vb 3
459 \& $obj\->match(1,0);
460 \& $obj\->match(2,0);
461 \& $obj\->match(3,0);
462 .Ve
463 .Sp
464 Consult the match table in "Smartmatch Operator" in perlop for
465 details of when overloading is invoked.
466 .IP \(bu 5
467 \&\fIDereferencing\fR
468 .Sp
469 .Vb 1
470 \& ${} @{} %{} &{} *{}
471 .Ve
472 .Sp
473 If these operators are not explicitly overloaded then they
474 work in the normal way, yielding the underlying scalar,
475 array, or whatever stores the object data (or the appropriate
476 error message if the dereference operator doesn\*(Aqt match it).
477 Defining a catch\-all \f(CW\*(Aqnomethod\*(Aq\fR (see below)
478 makes no difference to this as the catch\-all function will
479 not be called to implement a missing dereference operator.
480 .Sp
481 If a dereference operator is overloaded then it must return a
482 \&\fIreference\fR of the appropriate type (for example, the
483 subroutine for key \f(CW\*(Aq${}\*(Aq\fR should return a reference to a
484 scalar, not a scalar), or another object which overloads the
485 operator: that is, the subroutine only determines what is
486 dereferenced and the actual dereferencing is left to Perl.
487 As a special case, if the subroutine returns the object itself
488 then it will not be called again \- avoiding infinite recursion.
489 .IP \(bu 5
490 \&\fISpecial\fR
491 .Sp
492 .Vb 1
493 \& nomethod fallback =
494 .Ve
495 .Sp
496 See "Special Keys for \f(CW\*(C`use overload\*(C'\fR".
497 .SS "Magic Autogeneration"
498 .IX Subsection "Magic Autogeneration"
499 If a method for an operation is not found then Perl tries to
500 autogenerate a substitute implementation from the operations
501 that have been defined.
502 .PP
503 Note: the behaviour described in this section can be disabled
504 by setting \f(CW\*(C`fallback\*(C'\fR to FALSE (see "fallback").
505 .PP
506 In the following tables, numbers indicate priority.
507 For example, the table below states that,
508 if no implementation for \f(CW\*(Aq!\*(Aq\fR has been defined then Perl will
509 implement it using \f(CW\*(Aqbool\*(Aq\fR (that is, by inverting the value
510 returned by the method for \f(CW\*(Aqbool\*(Aq\fR);
511 if boolean conversion is also unimplemented then Perl will
512 use \f(CW\*(Aq0+\*(Aq\fR or, failing that, \f(CW\*(Aq""\*(Aq\fR.
513 .PP
514 .Vb 10
515 \& operator | can be autogenerated from
516 \& |
517 \& | 0+ "" bool . x
518 \& =========|==========================
519 \& 0+ | 1 2
520 \& "" | 1 2
521 \& bool | 1 2
522 \& int | 1 2 3
523 \& ! | 2 3 1
524 \& qr | 2 1 3
525 \& . | 2 1 3
526 \& x | 2 1 3
527 \& .= | 3 2 4 1
528 \& x= | 3 2 4 1
529 \& <> | 2 1 3
530 \& \-X | 2 1 3
531 .Ve
532 .PP
533 Note: The iterator (\f(CW\*(Aq<>\*(Aq\fR) and file test (\f(CW\*(Aq\-X\*(Aq\fR)
534 operators work as normal: if the operand is not a blessed glob or
535 IO reference then it is converted to a string (using the method
536 for \f(CW\*(Aq""\*(Aq\fR, \f(CW\*(Aq0+\*(Aq\fR, or \f(CW\*(Aqbool\*(Aq\fR) to be interpreted as a glob
537 or filename.
538 .PP
539 .Vb 10
540 \& operator | can be autogenerated from
541 \& |
542 \& | < <=> neg \-= \-
543 \& =========|==========================
544 \& neg | 1
545 \& \-= | 1
546 \& \-\- | 1 2
547 \& abs | a1 a2 b1 b2 [*]
548 \& < | 1
549 \& <= | 1
550 \& > | 1
551 \& >= | 1
552 \& == | 1
553 \& != | 1
554 \&
555 \& * one from [a1, a2] and one from [b1, b2]
556 .Ve
557 .PP
558 Just as numeric comparisons can be autogenerated from the method
559 for \f(CW\*(Aq<=>\*(Aq\fR, string comparisons can be autogenerated from
560 that for \f(CW\*(Aqcmp\*(Aq\fR:
561 .PP
562 .Vb 3
563 \& operators | can be autogenerated from
564 \& ====================|===========================
565 \& lt gt le ge eq ne | cmp
566 .Ve
567 .PP
568 Similarly, autogeneration for keys \f(CW\*(Aq+=\*(Aq\fR and \f(CW\*(Aq++\*(Aq\fR is analogous
569 to \f(CW\*(Aq\-=\*(Aq\fR and \f(CW\*(Aq\-\-\*(Aq\fR above:
570 .PP
571 .Vb 6
572 \& operator | can be autogenerated from
573 \& |
574 \& | += +
575 \& =========|==========================
576 \& += | 1
577 \& ++ | 1 2
578 .Ve
579 .PP
580 And other assignment variations are analogous to
581 \&\f(CW\*(Aq+=\*(Aq\fR and \f(CW\*(Aq\-=\*(Aq\fR (and similar to \f(CW\*(Aq.=\*(Aq\fR and \f(CW\*(Aqx=\*(Aq\fR above):
582 .PP
583 .Vb 3
584 \& operator || *= /= %= **= <<= >>= &= ^= |= &.= ^.= |.=
585 \& \-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-||\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
586 \& autogenerated from || * / % ** << >> & ^ | &. ^. |.
587 .Ve
588 .PP
589 Note also that the copy constructor (key \f(CW\*(Aq=\*(Aq\fR) may be
590 autogenerated, but only for objects based on scalars.
591 See "Copy Constructor".
592 .PP
593 \fIMinimal Set of Overloaded Operations\fR
594 .IX Subsection "Minimal Set of Overloaded Operations"
595 .PP
596 Since some operations can be automatically generated from others, there is
597 a minimal set of operations that need to be overloaded in order to have
598 the complete set of overloaded operations at one\*(Aqs disposal.
599 Of course, the autogenerated operations may not do exactly what the user
600 expects. The minimal set is:
601 .PP
602 .Vb 6
603 \& + \- * / % ** << >> x
604 \& <=> cmp
605 \& & | ^ ~ &. |. ^. ~.
606 \& atan2 cos sin exp log sqrt int
607 \& "" 0+ bool
608 \& ~~
609 .Ve
610 .PP
611 Of the conversions, only one of string, boolean or numeric is
612 needed because each can be generated from either of the other two.
613 .ie n .SS "Special Keys for ""use overload"""
614 .el .SS "Special Keys for \f(CWuse overload\fP"
615 .IX Subsection "Special Keys for use overload"
616 \fR\f(CI\*(C`nomethod\*(C'\fR\fI\fR
617 .IX Subsection "nomethod"
618 .PP
619 The \f(CW\*(Aqnomethod\*(Aq\fR key is used to specify a catch\-all function to
620 be called for any operator that is not individually overloaded.
621 The specified function will be passed four parameters.
622 The first three arguments coincide with those that would have been
623 passed to the corresponding method if it had been defined.
624 The fourth argument is the \f(CW\*(C`use overload\*(C'\fR key for that missing
625 method. If the "bitwise" feature is enabled (see feature),
626 a fifth TRUE argument is passed to subroutines handling \f(CW\*(C`&\*(C'\fR, \f(CW\*(C`|\*(C'\fR, \f(CW\*(C`^\*(C'\fR and \f(CW\*(C`~\*(C'\fR to indicate that the caller is expecting numeric behaviour.
627 .PP
628 For example, if \f(CW$a\fR is an object blessed into a package declaring
629 .PP
630 .Vb 1
631 \& use overload \*(Aqnomethod\*(Aq => \*(Aqcatch_all\*(Aq, # ...
632 .Ve
633 .PP
634 then the operation
635 .PP
636 .Vb 1
637 \& 3 + $a
638 .Ve
639 .PP
640 could (unless a method is specifically declared for the key
641 \&\f(CW\*(Aq+\*(Aq\fR) result in a call
642 .PP
643 .Vb 1
644 \& catch_all($a, 3, 1, \*(Aq+\*(Aq)
645 .Ve
646 .PP
647 See "How Perl Chooses an Operator Implementation".
648 .PP
649 \fR\f(CI\*(C`fallback\*(C'\fR\fI\fR
650 .IX Subsection "fallback"
651 .PP
652 The value assigned to the key \f(CW\*(Aqfallback\*(Aq\fR tells Perl how hard
653 it should try to find an alternative way to implement a missing
654 operator.
655 .IP \(bu 4
656 defined, but FALSE
657 .Sp
658 .Vb 1
659 \& use overload "fallback" => 0, # ... ;
660 .Ve
661 .Sp
662 This disables "Magic Autogeneration".
663 .IP \(bu 4
664 \&\f(CW\*(C`undef\*(C'\fR
665 .Sp
666 In the default case where no value is explicitly assigned to
667 \&\f(CW\*(C`fallback\*(C'\fR, magic autogeneration is enabled.
668 .IP \(bu 4
669 TRUE
670 .Sp
671 The same as for \f(CW\*(C`undef\*(C'\fR, but if a missing operator cannot be
672 autogenerated then, instead of issuing an error message, Perl
673 is allowed to revert to what it would have done for that
674 operator if there had been no \f(CW\*(C`use overload\*(C'\fR directive.
675 .Sp
676 Note: in most cases, particularly the "Copy Constructor",
677 this is unlikely to be appropriate behaviour.
678 .PP
679 See "How Perl Chooses an Operator Implementation".
680 .PP
681 \fICopy Constructor\fR
682 .IX Subsection "Copy Constructor"
683 .PP
684 As mentioned above,
685 this operation is called when a mutator is applied to a reference
686 that shares its object with some other reference.
687 For example, if \f(CW$b\fR is mathemagical, and \f(CW\*(Aq++\*(Aq\fR is overloaded
688 with \f(CW\*(Aqincr\*(Aq\fR, and \f(CW\*(Aq=\*(Aq\fR is overloaded with \f(CW\*(Aqclone\*(Aq\fR, then the
689 code
690 .PP
691 .Vb 3
692 \& $a = $b;
693 \& # ... (other code which does not modify $a or $b) ...
694 \& ++$b;
695 .Ve
696 .PP
697 would be executed in a manner equivalent to
698 .PP
699 .Vb 4
700 \& $a = $b;
701 \& # ...
702 \& $b = $b\->clone(undef, "");
703 \& $b\->incr(undef, "");
704 .Ve
705 .PP
706 Note:
707 .IP \(bu 4
708 The subroutine for \f(CW\*(Aq=\*(Aq\fR does not overload the Perl assignment
709 operator: it is used only to allow mutators to work as described
710 here. (See "Assignments" above.)
711 .IP \(bu 4
712 As for other operations, the subroutine implementing \*(Aq=\*(Aq is passed
713 three arguments, though the last two are always \f(CW\*(C`undef\*(C'\fR and \f(CW\*(Aq\*(Aq\fR.
714 .IP \(bu 4
715 The copy constructor is called only before a call to a function
716 declared to implement a mutator, for example, if \f(CW\*(C`++$b;\*(C'\fR in the
717 code above is effected via a method declared for key \f(CW\*(Aq++\*(Aq\fR
718 (or \*(Aqnomethod\*(Aq, passed \f(CW\*(Aq++\*(Aq\fR as the fourth argument) or, by
719 autogeneration, \f(CW\*(Aq+=\*(Aq\fR.
720 It is not called if the increment operation is effected by a call
721 to the method for \f(CW\*(Aq+\*(Aq\fR since, in the equivalent code,
722 .Sp
723 .Vb 2
724 \& $a = $b;
725 \& $b = $b + 1;
726 .Ve
727 .Sp
728 the data referred to by \f(CW$a\fR is unchanged by the assignment to
729 \&\f(CW$b\fR of a reference to new object data.
730 .IP \(bu 4
731 The copy constructor is not called if Perl determines that it is
732 unnecessary because there is no other reference to the data being
733 modified.
734 .IP \(bu 4
735 If \f(CW\*(Aqfallback\*(Aq\fR is undefined or TRUE then a copy constructor
736 can be autogenerated, but only for objects based on scalars.
737 In other cases it needs to be defined explicitly.
738 Where an object\*(Aqs data is stored as, for example, an array of
739 scalars, the following might be appropriate:
740 .Sp
741 .Vb 1
742 \& use overload \*(Aq=\*(Aq => sub { bless [ @{$_[0]} ] }, # ...
743 .Ve
744 .IP \(bu 4
745 If \f(CW\*(Aqfallback\*(Aq\fR is TRUE and no copy constructor is defined then,
746 for objects not based on scalars, Perl may silently fall back on
747 simple assignment \- that is, assignment of the object reference.
748 In effect, this disables the copy constructor mechanism since
749 no new copy of the object data is created.
750 This is almost certainly not what you want.
751 (It is, however, consistent: for example, Perl\*(Aqs fallback for the
752 \&\f(CW\*(C`++\*(C'\fR operator is to increment the reference itself.)
753 .SS "How Perl Chooses an Operator Implementation"
754 .IX Subsection "How Perl Chooses an Operator Implementation"
755 Which is checked first, \f(CW\*(C`nomethod\*(C'\fR or \f(CW\*(C`fallback\*(C'\fR?
756 If the two operands of an operator are of different types and
757 both overload the operator, which implementation is used?
758 The following are the precedence rules:
759 .IP 1. 4
760 If the first operand has declared a subroutine to overload the
761 operator then use that implementation.
762 .IP 2. 4
763 Otherwise, if fallback is TRUE or undefined for the
764 first operand then see if the
765 rules for autogeneration
766 allows another of its operators to be used instead.
767 .IP 3. 4
768 Unless the operator is an assignment (\f(CW\*(C`+=\*(C'\fR, \f(CW\*(C`\-=\*(C'\fR, etc.),
769 repeat step (1) in respect of the second operand.
770 .IP 4. 4
771 Repeat Step (2) in respect of the second operand.
772 .IP 5. 4
773 If the first operand has a "nomethod" method then use that.
774 .IP 6. 4
775 If the second operand has a "nomethod" method then use that.
776 .IP 7. 4
777 If \f(CW\*(C`fallback\*(C'\fR is TRUE for both operands
778 then perform the usual operation for the operator,
779 treating the operands as numbers, strings, or booleans
780 as appropriate for the operator (see note).
781 .IP 8. 4
782 Nothing worked \- die.
783 .PP
784 Where there is only one operand (or only one operand with
785 overloading) the checks in respect of the other operand above are
786 skipped.
787 .PP
788 There are exceptions to the above rules for dereference operations
789 (which, if Step 1 fails, always fall back to the normal, built\-in
790 implementations \- see Dereferencing), and for \f(CW\*(C`~~\*(C'\fR (which has its
791 own set of rules \- see \f(CW\*(C`Matching\*(C'\fR under "Overloadable Operations"
792 above).
793 .PP
794 Note on Step 7: some operators have a different semantic depending
795 on the type of their operands.
796 As there is no way to instruct Perl to treat the operands as, e.g.,
797 numbers instead of strings, the result here may not be what you
798 expect.
799 See "BUGS AND PITFALLS".
800 .SS "Losing Overloading"
801 .IX Subsection "Losing Overloading"
802 The restriction for the comparison operation is that even if, for example,
803 \&\f(CW\*(C`cmp\*(C'\fR should return a blessed reference, the autogenerated \f(CW\*(C`lt\*(C'\fR
804 function will produce only a standard logical value based on the
805 numerical value of the result of \f(CW\*(C`cmp\*(C'\fR. In particular, a working
806 numeric conversion is needed in this case (possibly expressed in terms of
807 other conversions).
808 .PP
809 Similarly, \f(CW\*(C`.=\*(C'\fR and \f(CW\*(C`x=\*(C'\fR operators lose their mathemagical properties
810 if the string conversion substitution is applied.
811 .PP
812 When you \fBchop()\fR a mathemagical object it is promoted to a string and its
813 mathemagical properties are lost. The same can happen with other
814 operations as well.
815 .SS "Inheritance and Overloading"
816 .IX Subsection "Inheritance and Overloading"
817 Overloading respects inheritance via the \f(CW@ISA\fR hierarchy.
818 Inheritance interacts with overloading in two ways.
819 .ie n .IP "Method names in the ""use overload"" directive" 4
820 .el .IP "Method names in the \f(CWuse overload\fR directive" 4
821 .IX Item "Method names in the use overload directive"
822 If \f(CW\*(C`value\*(C'\fR in
823 .Sp
824 .Vb 1
825 \& use overload key => value;
826 .Ve
827 .Sp
828 is a string, it is interpreted as a method name \- which may
829 (in the usual way) be inherited from another class.
830 .IP "Overloading of an operation is inherited by derived classes" 4
831 .IX Item "Overloading of an operation is inherited by derived classes"
832 Any class derived from an overloaded class is also overloaded
833 and inherits its operator implementations.
834 If the same operator is overloaded in more than one ancestor
835 then the implementation is determined by the usual inheritance
836 rules.
837 .Sp
838 For example, if \f(CW\*(C`A\*(C'\fR inherits from \f(CW\*(C`B\*(C'\fR and \f(CW\*(C`C\*(C'\fR (in that order),
839 \&\f(CW\*(C`B\*(C'\fR overloads \f(CW\*(C`+\*(C'\fR with \f(CW\*(C`\e&D::plus_sub\*(C'\fR, and \f(CW\*(C`C\*(C'\fR overloads
840 \&\f(CW\*(C`+\*(C'\fR by \f(CW"plus_meth"\fR, then the subroutine \f(CW\*(C`D::plus_sub\*(C'\fR will
841 be called to implement operation \f(CW\*(C`+\*(C'\fR for an object in package \f(CW\*(C`A\*(C'\fR.
842 .PP
843 Note that in Perl version prior to 5.18 inheritance of the \f(CW\*(C`fallback\*(C'\fR key
844 was not governed by the above rules. The value of \f(CW\*(C`fallback\*(C'\fR in the first
845 overloaded ancestor was used. This was fixed in 5.18 to follow the usual
846 rules of inheritance.
847 .SS "Run\-time Overloading"
848 .IX Subsection "Run-time Overloading"
849 Since all \f(CW\*(C`use\*(C'\fR directives are executed at compile\-time, the only way to
850 change overloading during run\-time is to
851 .PP
852 .Vb 1
853 \& eval \*(Aquse overload "+" => \e&addmethod\*(Aq;
854 .Ve
855 .PP
856 You can also use
857 .PP
858 .Vb 1
859 \& eval \*(Aqno overload "+", "\-\-", "<="\*(Aq;
860 .Ve
861 .PP
862 though the use of these constructs during run\-time is questionable.
863 .SS "Public Functions"
864 .IX Subsection "Public Functions"
865 Package \f(CW\*(C`overload.pm\*(C'\fR provides the following public functions:
866 .IP overload::StrVal(arg) 5
867 .IX Item "overload::StrVal(arg)"
868 Gives the string value of \f(CW\*(C`arg\*(C'\fR as in the
869 absence of stringify overloading. If you
870 are using this to get the address of a reference (useful for checking if two
871 references point to the same thing) then you may be better off using
872 \&\f(CWbuiltin::refaddr()\fR or \f(CWScalar::Util::refaddr()\fR, which are faster.
873 .IP overload::Overloaded(arg) 5
874 .IX Item "overload::Overloaded(arg)"
875 Returns true if \f(CW\*(C`arg\*(C'\fR is subject to overloading of some operations.
876 .IP overload::Method(obj,op) 5
877 .IX Item "overload::Method(obj,op)"
878 Returns \f(CW\*(C`undef\*(C'\fR or a reference to the method that implements \f(CW\*(C`op\*(C'\fR.
879 .Sp
880 Such a method always takes three arguments, which will be enforced if
881 it is an XS method.
882 .SS "Overloading Constants"
883 .IX Subsection "Overloading Constants"
884 For some applications, the Perl parser mangles constants too much.
885 It is possible to hook into this process via \f(CWoverload::constant()\fR
886 and \f(CWoverload::remove_constant()\fR functions.
887 .PP
888 These functions take a hash as an argument. The recognized keys of this hash
889 are:
890 .IP integer 8
891 .IX Item "integer"
892 to overload integer constants,
893 .IP float 8
894 .IX Item "float"
895 to overload floating point constants,
896 .IP binary 8
897 .IX Item "binary"
898 to overload octal and hexadecimal constants,
899 .IP q 8
900 .IX Item "q"
901 to overload \f(CW\*(C`q\*(C'\fR\-quoted strings, constant pieces of \f(CW\*(C`qq\*(C'\fR\- and \f(CW\*(C`qx\*(C'\fR\-quoted
902 strings and here\-documents,
903 .IP qr 8
904 .IX Item "qr"
905 to overload constant pieces of regular expressions.
906 .PP
907 The corresponding values are references to functions which take three arguments:
908 the first one is the \fIinitial\fR string form of the constant, the second one
909 is how Perl interprets this constant, the third one is how the constant is used.
910 Note that the initial string form does not
911 contain string delimiters, and has backslashes in backslash\-delimiter
912 combinations stripped (thus the value of delimiter is not relevant for
913 processing of this string). The return value of this function is how this
914 constant is going to be interpreted by Perl. The third argument is undefined
915 unless for overloaded \f(CW\*(C`q\*(C'\fR\- and \f(CW\*(C`qr\*(C'\fR\- constants, it is \f(CW\*(C`q\*(C'\fR in single\-quote
916 context (comes from strings, regular expressions, and single\-quote HERE
917 documents), it is \f(CW\*(C`tr\*(C'\fR for arguments of \f(CW\*(C`tr\*(C'\fR/\f(CW\*(C`y\*(C'\fR operators,
918 it is \f(CW\*(C`s\*(C'\fR for right\-hand side of \f(CW\*(C`s\*(C'\fR\-operator, and it is \f(CW\*(C`qq\*(C'\fR otherwise.
919 .PP
920 Since an expression \f(CW"ab$cd,,"\fR is just a shortcut for \f(CW\*(Aqab\*(Aq . $cd . \*(Aq,,\*(Aq\fR,
921 it is expected that overloaded constant strings are equipped with reasonable
922 overloaded catenation operator, otherwise absurd results will result.
923 Similarly, negative numbers are considered as negations of positive constants.
924 .PP
925 Note that it is probably meaningless to call the functions \fBoverload::constant()\fR
926 and \fBoverload::remove_constant()\fR from anywhere but \fBimport()\fR and \fBunimport()\fR methods.
927 From these methods they may be called as
928 .PP
929 .Vb 6
930 \& sub import {
931 \& shift;
932 \& return unless @_;
933 \& die "unknown import: @_" unless @_ == 1 and $_[0] eq \*(Aq:constant\*(Aq;
934 \& overload::constant integer => sub {Math::BigInt\->new(shift)};
935 \& }
936 .Ve
937 .SH IMPLEMENTATION
938 .IX Header "IMPLEMENTATION"
939 What follows is subject to change RSN.
940 .PP
941 The table of methods for all operations is cached in magic for the
942 symbol table hash for the package. The cache is invalidated during
943 processing of \f(CW\*(C`use overload\*(C'\fR, \f(CW\*(C`no overload\*(C'\fR, new function
944 definitions, and changes in \f(CW@ISA\fR.
945 .PP
946 (Every SVish thing has a magic queue, and magic is an entry in that
947 queue. This is how a single variable may participate in multiple
948 forms of magic simultaneously. For instance, environment variables
949 regularly have two forms at once: their \f(CW%ENV\fR magic and their taint
950 magic. However, the magic which implements overloading is applied to
951 the stashes, which are rarely used directly, thus should not slow down
952 Perl.)
953 .PP
954 If a package uses overload, it carries a special flag. This flag is also
955 set when new functions are defined or \f(CW@ISA\fR is modified. There will be a
956 slight speed penalty on the very first operation thereafter that supports
957 overloading, while the overload tables are updated. If there is no
958 overloading present, the flag is turned off. Thus the only speed penalty
959 thereafter is the checking of this flag.
960 .PP
961 It is expected that arguments to methods that are not explicitly supposed
962 to be changed are constant (but this is not enforced).
963 .SH COOKBOOK
964 .IX Header "COOKBOOK"
965 Please add examples to what follows!
966 .SS "Two\-face Scalars"
967 .IX Subsection "Two-face Scalars"
968 Put this in \fItwo_face.pm\fR in your Perl library directory:
969 .PP
970 .Vb 6
971 \& package two_face; # Scalars with separate string and
972 \& # numeric values.
973 \& sub new { my $p = shift; bless [@_], $p }
974 \& use overload \*(Aq""\*(Aq => \e&str, \*(Aq0+\*(Aq => \e&num, fallback => 1;
975 \& sub num {shift\->[1]}
976 \& sub str {shift\->[0]}
977 .Ve
978 .PP
979 Use it as follows:
980 .PP
981 .Vb 4
982 \& require two_face;
983 \& my $seven = two_face\->new("vii", 7);
984 \& printf "seven=$seven, seven=%d, eight=%d\en", $seven, $seven+1;
985 \& print "seven contains \*(Aqi\*(Aq\en" if $seven =~ /i/;
986 .Ve
987 .PP
988 (The second line creates a scalar which has both a string value, and a
989 numeric value.) This prints:
990 .PP
991 .Vb 2
992 \& seven=vii, seven=7, eight=8
993 \& seven contains \*(Aqi\*(Aq
994 .Ve
995 .SS "Two\-face References"
996 .IX Subsection "Two-face References"
997 Suppose you want to create an object which is accessible as both an
998 array reference and a hash reference.
999 .PP
1000 .Vb 12
1001 \& package two_refs;
1002 \& use overload \*(Aq%{}\*(Aq => \e&gethash, \*(Aq@{}\*(Aq => sub { $ {shift()} };
1003 \& sub new {
1004 \& my $p = shift;
1005 \& bless \e [@_], $p;
1006 \& }
1007 \& sub gethash {
1008 \& my %h;
1009 \& my $self = shift;
1010 \& tie %h, ref $self, $self;
1011 \& \e%h;
1012 \& }
1013 \&
1014 \& sub TIEHASH { my $p = shift; bless \e shift, $p }
1015 \& my %fields;
1016 \& my $i = 0;
1017 \& $fields{$_} = $i++ foreach qw{zero one two three};
1018 \& sub STORE {
1019 \& my $self = ${shift()};
1020 \& my $key = $fields{shift()};
1021 \& defined $key or die "Out of band access";
1022 \& $$self\->[$key] = shift;
1023 \& }
1024 \& sub FETCH {
1025 \& my $self = ${shift()};
1026 \& my $key = $fields{shift()};
1027 \& defined $key or die "Out of band access";
1028 \& $$self\->[$key];
1029 \& }
1030 .Ve
1031 .PP
1032 Now one can access an object using both the array and hash syntax:
1033 .PP
1034 .Vb 3
1035 \& my $bar = two_refs\->new(3,4,5,6);
1036 \& $bar\->[2] = 11;
1037 \& $bar\->{two} == 11 or die \*(Aqbad hash fetch\*(Aq;
1038 .Ve
1039 .PP
1040 Note several important features of this example. First of all, the
1041 \&\fIactual\fR type of \f(CW$bar\fR is a scalar reference, and we do not overload
1042 the scalar dereference. Thus we can get the \fIactual\fR non\-overloaded
1043 contents of \f(CW$bar\fR by just using \f(CW$$bar\fR (what we do in functions which
1044 overload dereference). Similarly, the object returned by the
1045 \&\fBTIEHASH()\fR method is a scalar reference.
1046 .PP
1047 Second, we create a new tied hash each time the hash syntax is used.
1048 This allows us not to worry about a possibility of a reference loop,
1049 which would lead to a memory leak.
1050 .PP
1051 Both these problems can be cured. Say, if we want to overload hash
1052 dereference on a reference to an object which is \fIimplemented\fR as a
1053 hash itself, the only problem one has to circumvent is how to access
1054 this \fIactual\fR hash (as opposed to the \fIvirtual\fR hash exhibited by the
1055 overloaded dereference operator). Here is one possible fetching routine:
1056 .PP
1057 .Vb 8
1058 \& sub access_hash {
1059 \& my ($self, $key) = (shift, shift);
1060 \& my $class = ref $self;
1061 \& bless $self, \*(Aqoverload::dummy\*(Aq; # Disable overloading of %{}
1062 \& my $out = $self\->{$key};
1063 \& bless $self, $class; # Restore overloading
1064 \& $out;
1065 \& }
1066 .Ve
1067 .PP
1068 To remove creation of the tied hash on each access, one may an extra
1069 level of indirection which allows a non\-circular structure of references:
1070 .PP
1071 .Vb 4
1072 \& package two_refs1;
1073 \& use overload
1074 \& \*(Aq%{}\*(Aq => sub { ${shift()}\->[1] },
1075 \& \*(Aq@{}\*(Aq => sub { ${shift()}\->[0] };
1076 \&
1077 \& sub new {
1078 \& my $p = shift;
1079 \& my $a = [@_];
1080 \& my %h;
1081 \& tie %h, $p, $a;
1082 \& bless \e [$a, \e%h], $p;
1083 \& }
1084 \& sub gethash {
1085 \& my %h;
1086 \& my $self = shift;
1087 \& tie %h, ref $self, $self;
1088 \& \e%h;
1089 \& }
1090 \&
1091 \& sub TIEHASH { my $p = shift; bless \e shift, $p }
1092 \& my %fields;
1093 \& my $i = 0;
1094 \& $fields{$_} = $i++ foreach qw{zero one two three};
1095 \& sub STORE {
1096 \& my $a = ${shift()};
1097 \& my $key = $fields{shift()};
1098 \& defined $key or die "Out of band access";
1099 \& $a\->[$key] = shift;
1100 \& }
1101 \& sub FETCH {
1102 \& my $a = ${shift()};
1103 \& my $key = $fields{shift()};
1104 \& defined $key or die "Out of band access";
1105 \& $a\->[$key];
1106 \& }
1107 .Ve
1108 .PP
1109 Now if \f(CW$baz\fR is overloaded like this, then \f(CW$baz\fR is a reference to a
1110 reference to the intermediate array, which keeps a reference to an
1111 actual array, and the access hash. The \fBtie()\fRing object for the access
1112 hash is a reference to a reference to the actual array, so
1113 .IP \(bu 4
1114 There are no loops of references.
1115 .IP \(bu 4
1116 Both "objects" which are blessed into the class \f(CW\*(C`two_refs1\*(C'\fR are
1117 references to a reference to an array, thus references to a \fIscalar\fR.
1118 Thus the accessor expression \f(CW\*(C`$$foo\->[$ind]\*(C'\fR involves no
1119 overloaded operations.
1120 .SS "Symbolic Calculator"
1121 .IX Subsection "Symbolic Calculator"
1122 Put this in \fIsymbolic.pm\fR in your Perl library directory:
1123 .PP
1124 .Vb 2
1125 \& package symbolic; # Primitive symbolic calculator
1126 \& use overload nomethod => \e&wrap;
1127 \&
1128 \& sub new { shift; bless [\*(Aqn\*(Aq, @_] }
1129 \& sub wrap {
1130 \& my ($obj, $other, $inv, $meth) = @_;
1131 \& ($obj, $other) = ($other, $obj) if $inv;
1132 \& bless [$meth, $obj, $other];
1133 \& }
1134 .Ve
1135 .PP
1136 This module is very unusual as overloaded modules go: it does not
1137 provide any usual overloaded operators, instead it provides an
1138 implementation for \f(CW"nomethod"\fR. In this example the \f(CW\*(C`nomethod\*(C'\fR
1139 subroutine returns an object which encapsulates operations done over
1140 the objects: \f(CW\*(C`symbolic\->new(3)\*(C'\fR contains \f(CW\*(C`[\*(Aqn\*(Aq, 3]\*(C'\fR, \f(CW\*(C`2 +
1141 symbolic\->new(3)\*(C'\fR contains \f(CW\*(C`[\*(Aq+\*(Aq, 2, [\*(Aqn\*(Aq, 3]]\*(C'\fR.
1142 .PP
1143 Here is an example of the script which "calculates" the side of
1144 circumscribed octagon using the above package:
1145 .PP
1146 .Vb 4
1147 \& require symbolic;
1148 \& my $iter = 1; # 2**($iter+2) = 8
1149 \& my $side = symbolic\->new(1);
1150 \& my $cnt = $iter;
1151 \&
1152 \& while ($cnt\-\-) {
1153 \& $side = (sqrt(1 + $side**2) \- 1)/$side;
1154 \& }
1155 \& print "OK\en";
1156 .Ve
1157 .PP
1158 The value of \f(CW$side\fR is
1159 .PP
1160 .Vb 2
1161 \& [\*(Aq/\*(Aq, [\*(Aq\-\*(Aq, [\*(Aqsqrt\*(Aq, [\*(Aq+\*(Aq, 1, [\*(Aq**\*(Aq, [\*(Aqn\*(Aq, 1], 2]],
1162 \& undef], 1], [\*(Aqn\*(Aq, 1]]
1163 .Ve
1164 .PP
1165 Note that while we obtained this value using a nice little script,
1166 there is no simple way to \fIuse\fR this value. In fact this value may
1167 be inspected in debugger (see perldebug), but only if
1168 \&\f(CW\*(C`bareStringify\*(C'\fR \fBO\fRption is set, and not via \f(CW\*(C`p\*(C'\fR command.
1169 .PP
1170 If one attempts to print this value, then the overloaded operator
1171 \&\f(CW""\fR will be called, which will call \f(CW\*(C`nomethod\*(C'\fR operator. The
1172 result of this operator will be stringified again, but this result is
1173 again of type \f(CW\*(C`symbolic\*(C'\fR, which will lead to an infinite loop.
1174 .PP
1175 Add a pretty\-printer method to the module \fIsymbolic.pm\fR:
1176 .PP
1177 .Vb 8
1178 \& sub pretty {
1179 \& my ($meth, $a, $b) = @{+shift};
1180 \& $a = \*(Aqu\*(Aq unless defined $a;
1181 \& $b = \*(Aqu\*(Aq unless defined $b;
1182 \& $a = $a\->pretty if ref $a;
1183 \& $b = $b\->pretty if ref $b;
1184 \& "[$meth $a $b]";
1185 \& }
1186 .Ve
1187 .PP
1188 Now one can finish the script by
1189 .PP
1190 .Vb 1
1191 \& print "side = ", $side\->pretty, "\en";
1192 .Ve
1193 .PP
1194 The method \f(CW\*(C`pretty\*(C'\fR is doing object\-to\-string conversion, so it
1195 is natural to overload the operator \f(CW""\fR using this method. However,
1196 inside such a method it is not necessary to pretty\-print the
1197 \&\fIcomponents\fR \f(CW$a\fR and \f(CW$b\fR of an object. In the above subroutine
1198 \&\f(CW"[$meth $a $b]"\fR is a catenation of some strings and components \f(CW$a\fR
1199 and \f(CW$b\fR. If these components use overloading, the catenation operator
1200 will look for an overloaded operator \f(CW\*(C`.\*(C'\fR; if not present, it will
1201 look for an overloaded operator \f(CW""\fR. Thus it is enough to use
1202 .PP
1203 .Vb 7
1204 \& use overload nomethod => \e&wrap, \*(Aq""\*(Aq => \e&str;
1205 \& sub str {
1206 \& my ($meth, $a, $b) = @{+shift};
1207 \& $a = \*(Aqu\*(Aq unless defined $a;
1208 \& $b = \*(Aqu\*(Aq unless defined $b;
1209 \& "[$meth $a $b]";
1210 \& }
1211 .Ve
1212 .PP
1213 Now one can change the last line of the script to
1214 .PP
1215 .Vb 1
1216 \& print "side = $side\en";
1217 .Ve
1218 .PP
1219 which outputs
1220 .PP
1221 .Vb 1
1222 \& side = [/ [\- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
1223 .Ve
1224 .PP
1225 and one can inspect the value in debugger using all the possible
1226 methods.
1227 .PP
1228 Something is still amiss: consider the loop variable \f(CW$cnt\fR of the
1229 script. It was a number, not an object. We cannot make this value of
1230 type \f(CW\*(C`symbolic\*(C'\fR, since then the loop will not terminate.
1231 .PP
1232 Indeed, to terminate the cycle, the \f(CW$cnt\fR should become false.
1233 However, the operator \f(CW\*(C`bool\*(C'\fR for checking falsity is overloaded (this
1234 time via overloaded \f(CW""\fR), and returns a long string, thus any object
1235 of type \f(CW\*(C`symbolic\*(C'\fR is true. To overcome this, we need a way to
1236 compare an object to 0. In fact, it is easier to write a numeric
1237 conversion routine.
1238 .PP
1239 Here is the text of \fIsymbolic.pm\fR with such a routine added (and
1240 slightly modified \fBstr()\fR):
1241 .PP
1242 .Vb 3
1243 \& package symbolic; # Primitive symbolic calculator
1244 \& use overload
1245 \& nomethod => \e&wrap, \*(Aq""\*(Aq => \e&str, \*(Aq0+\*(Aq => \e&num;
1246 \&
1247 \& sub new { shift; bless [\*(Aqn\*(Aq, @_] }
1248 \& sub wrap {
1249 \& my ($obj, $other, $inv, $meth) = @_;
1250 \& ($obj, $other) = ($other, $obj) if $inv;
1251 \& bless [$meth, $obj, $other];
1252 \& }
1253 \& sub str {
1254 \& my ($meth, $a, $b) = @{+shift};
1255 \& $a = \*(Aqu\*(Aq unless defined $a;
1256 \& if (defined $b) {
1257 \& "[$meth $a $b]";
1258 \& } else {
1259 \& "[$meth $a]";
1260 \& }
1261 \& }
1262 \& my %subr = (
1263 \& n => sub {$_[0]},
1264 \& sqrt => sub {sqrt $_[0]},
1265 \& \*(Aq\-\*(Aq => sub {shift() \- shift()},
1266 \& \*(Aq+\*(Aq => sub {shift() + shift()},
1267 \& \*(Aq/\*(Aq => sub {shift() / shift()},
1268 \& \*(Aq*\*(Aq => sub {shift() * shift()},
1269 \& \*(Aq**\*(Aq => sub {shift() ** shift()},
1270 \& );
1271 \& sub num {
1272 \& my ($meth, $a, $b) = @{+shift};
1273 \& my $subr = $subr{$meth}
1274 \& or die "Do not know how to ($meth) in symbolic";
1275 \& $a = $a\->num if ref $a eq _\|_PACKAGE_\|_;
1276 \& $b = $b\->num if ref $b eq _\|_PACKAGE_\|_;
1277 \& $subr\->($a,$b);
1278 \& }
1279 .Ve
1280 .PP
1281 All the work of numeric conversion is done in \f(CW%subr\fR and \fBnum()\fR. Of
1282 course, \f(CW%subr\fR is not complete, it contains only operators used in the
1283 example below. Here is the extra\-credit question: why do we need an
1284 explicit recursion in \fBnum()\fR? (Answer is at the end of this section.)
1285 .PP
1286 Use this module like this:
1287 .PP
1288 .Vb 4
1289 \& require symbolic;
1290 \& my $iter = symbolic\->new(2); # 16\-gon
1291 \& my $side = symbolic\->new(1);
1292 \& my $cnt = $iter;
1293 \&
1294 \& while ($cnt) {
1295 \& $cnt = $cnt \- 1; # Mutator \*(Aq\-\-\*(Aq not implemented
1296 \& $side = (sqrt(1 + $side**2) \- 1)/$side;
1297 \& }
1298 \& printf "%s=%f\en", $side, $side;
1299 \& printf "pi=%f\en", $side*(2**($iter+2));
1300 .Ve
1301 .PP
1302 It prints (without so many line breaks)
1303 .PP
1304 .Vb 4
1305 \& [/ [\- [sqrt [+ 1 [** [/ [\- [sqrt [+ 1 [** [n 1] 2]]] 1]
1306 \& [n 1]] 2]]] 1]
1307 \& [/ [\- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912
1308 \& pi=3.182598
1309 .Ve
1310 .PP
1311 The above module is very primitive. It does not implement
1312 mutator methods (\f(CW\*(C`++\*(C'\fR, \f(CW\*(C`\-=\*(C'\fR and so on), does not do deep copying
1313 (not required without mutators!), and implements only those arithmetic
1314 operations which are used in the example.
1315 .PP
1316 To implement most arithmetic operations is easy; one should just use
1317 the tables of operations, and change the code which fills \f(CW%subr\fR to
1318 .PP
1319 .Vb 12
1320 \& my %subr = ( \*(Aqn\*(Aq => sub {$_[0]} );
1321 \& foreach my $op (split " ", $overload::ops{with_assign}) {
1322 \& $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1323 \& }
1324 \& my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1325 \& foreach my $op (split " ", "@overload::ops{ @bins }") {
1326 \& $subr{$op} = eval "sub {shift() $op shift()}";
1327 \& }
1328 \& foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1329 \& print "defining \*(Aq$op\*(Aq\en";
1330 \& $subr{$op} = eval "sub {$op shift()}";
1331 \& }
1332 .Ve
1333 .PP
1334 Since subroutines implementing assignment operators are not required
1335 to modify their operands (see "Overloadable Operations" above),
1336 we do not need anything special to make \f(CW\*(C`+=\*(C'\fR and friends work,
1337 besides adding these operators to \f(CW%subr\fR and defining a copy
1338 constructor (needed since Perl has no way to know that the
1339 implementation of \f(CW\*(Aq+=\*(Aq\fR does not mutate the argument \-
1340 see "Copy Constructor").
1341 .PP
1342 To implement a copy constructor, add \f(CW\*(C`\*(Aq=\*(Aq => \e&cpy\*(C'\fR to \f(CW\*(C`use overload\*(C'\fR
1343 line, and code (this code assumes that mutators change things one level
1344 deep only, so recursive copying is not needed):
1345 .PP
1346 .Vb 4
1347 \& sub cpy {
1348 \& my $self = shift;
1349 \& bless [@$self], ref $self;
1350 \& }
1351 .Ve
1352 .PP
1353 To make \f(CW\*(C`++\*(C'\fR and \f(CW\*(C`\-\-\*(C'\fR work, we need to implement actual mutators,
1354 either directly, or in \f(CW\*(C`nomethod\*(C'\fR. We continue to do things inside
1355 \&\f(CW\*(C`nomethod\*(C'\fR, thus add
1356 .PP
1357 .Vb 4
1358 \& if ($meth eq \*(Aq++\*(Aq or $meth eq \*(Aq\-\-\*(Aq) {
1359 \& @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
1360 \& return $obj;
1361 \& }
1362 .Ve
1363 .PP
1364 after the first line of \fBwrap()\fR. This is not a most effective
1365 implementation, one may consider
1366 .PP
1367 .Vb 1
1368 \& sub inc { $_[0] = bless [\*(Aq++\*(Aq, shift, 1]; }
1369 .Ve
1370 .PP
1371 instead.
1372 .PP
1373 As a final remark, note that one can fill \f(CW%subr\fR by
1374 .PP
1375 .Vb 10
1376 \& my %subr = ( \*(Aqn\*(Aq => sub {$_[0]} );
1377 \& foreach my $op (split " ", $overload::ops{with_assign}) {
1378 \& $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}";
1379 \& }
1380 \& my @bins = qw(binary 3way_comparison num_comparison str_comparison);
1381 \& foreach my $op (split " ", "@overload::ops{ @bins }") {
1382 \& $subr{$op} = eval "sub {shift() $op shift()}";
1383 \& }
1384 \& foreach my $op (split " ", "@overload::ops{qw(unary func)}") {
1385 \& $subr{$op} = eval "sub {$op shift()}";
1386 \& }
1387 \& $subr{\*(Aq++\*(Aq} = $subr{\*(Aq+\*(Aq};
1388 \& $subr{\*(Aq\-\-\*(Aq} = $subr{\*(Aq\-\*(Aq};
1389 .Ve
1390 .PP
1391 This finishes implementation of a primitive symbolic calculator in
1392 50 lines of Perl code. Since the numeric values of subexpressions
1393 are not cached, the calculator is very slow.
1394 .PP
1395 Here is the answer for the exercise: In the case of \fBstr()\fR, we need no
1396 explicit recursion since the overloaded \f(CW\*(C`.\*(C'\fR\-operator will fall back
1397 to an existing overloaded operator \f(CW""\fR. Overloaded arithmetic
1398 operators \fIdo not\fR fall back to numeric conversion if \f(CW\*(C`fallback\*(C'\fR is
1399 not explicitly requested. Thus without an explicit recursion \fBnum()\fR
1400 would convert \f(CW\*(C`[\*(Aq+\*(Aq, $a, $b]\*(C'\fR to \f(CW\*(C`$a + $b\*(C'\fR, which would just rebuild
1401 the argument of \fBnum()\fR.
1402 .PP
1403 If you wonder why defaults for conversion are different for \fBstr()\fR and
1404 \&\fBnum()\fR, note how easy it was to write the symbolic calculator. This
1405 simplicity is due to an appropriate choice of defaults. One extra
1406 note: due to the explicit recursion \fBnum()\fR is more fragile than \fBsym()\fR:
1407 we need to explicitly check for the type of \f(CW$a\fR and \f(CW$b\fR. If components
1408 \&\f(CW$a\fR and \f(CW$b\fR happen to be of some related type, this may lead to problems.
1409 .SS "\fIReally\fP Symbolic Calculator"
1410 .IX Subsection "Really Symbolic Calculator"
1411 One may wonder why we call the above calculator symbolic. The reason
1412 is that the actual calculation of the value of expression is postponed
1413 until the value is \fIused\fR.
1414 .PP
1415 To see it in action, add a method
1416 .PP
1417 .Vb 5
1418 \& sub STORE {
1419 \& my $obj = shift;
1420 \& $#$obj = 1;
1421 \& @$obj\->[0,1] = (\*(Aq=\*(Aq, shift);
1422 \& }
1423 .Ve
1424 .PP
1425 to the package \f(CW\*(C`symbolic\*(C'\fR. After this change one can do
1426 .PP
1427 .Vb 3
1428 \& my $a = symbolic\->new(3);
1429 \& my $b = symbolic\->new(4);
1430 \& my $c = sqrt($a**2 + $b**2);
1431 .Ve
1432 .PP
1433 and the numeric value of \f(CW$c\fR becomes 5. However, after calling
1434 .PP
1435 .Vb 1
1436 \& $a\->STORE(12); $b\->STORE(5);
1437 .Ve
1438 .PP
1439 the numeric value of \f(CW$c\fR becomes 13. There is no doubt now that the module
1440 symbolic provides a \fIsymbolic\fR calculator indeed.
1441 .PP
1442 To hide the rough edges under the hood, provide a \fBtie()\fRd interface to the
1443 package \f(CW\*(C`symbolic\*(C'\fR. Add methods
1444 .PP
1445 .Vb 3
1446 \& sub TIESCALAR { my $pack = shift; $pack\->new(@_) }
1447 \& sub FETCH { shift }
1448 \& sub nop { } # Around a bug
1449 .Ve
1450 .PP
1451 (the bug, fixed in Perl 5.14, is described in "BUGS"). One can use this
1452 new interface as
1453 .PP
1454 .Vb 3
1455 \& tie $a, \*(Aqsymbolic\*(Aq, 3;
1456 \& tie $b, \*(Aqsymbolic\*(Aq, 4;
1457 \& $a\->nop; $b\->nop; # Around a bug
1458 \&
1459 \& my $c = sqrt($a**2 + $b**2);
1460 .Ve
1461 .PP
1462 Now numeric value of \f(CW$c\fR is 5. After \f(CW\*(C`$a = 12; $b = 5\*(C'\fR the numeric value
1463 of \f(CW$c\fR becomes 13. To insulate the user of the module add a method
1464 .PP
1465 .Vb 1
1466 \& sub vars { my $p = shift; tie($_, $p), $_\->nop foreach @_; }
1467 .Ve
1468 .PP
1469 Now
1470 .PP
1471 .Vb 3
1472 \& my ($a, $b);
1473 \& symbolic\->vars($a, $b);
1474 \& my $c = sqrt($a**2 + $b**2);
1475 \&
1476 \& $a = 3; $b = 4;
1477 \& printf "c5 %s=%f\en", $c, $c;
1478 \&
1479 \& $a = 12; $b = 5;
1480 \& printf "c13 %s=%f\en", $c, $c;
1481 .Ve
1482 .PP
1483 shows that the numeric value of \f(CW$c\fR follows changes to the values of \f(CW$a\fR
1484 and \f(CW$b\fR.
1485 .SH AUTHOR
1486 .IX Header "AUTHOR"
1487 Ilya Zakharevich <\[email protected]\-state.edu\fR>.
1488 .SH "SEE ALSO"
1489 .IX Header "SEE ALSO"
1490 The \f(CW\*(C`overloading\*(C'\fR pragma can be used to enable or disable overloaded
1491 operations within a lexical scope \- see overloading.
1492 .SH DIAGNOSTICS
1493 .IX Header "DIAGNOSTICS"
1494 When Perl is run with the \fB\-Do\fR switch or its equivalent, overloading
1495 induces diagnostic messages.
1496 .PP
1497 Using the \f(CW\*(C`m\*(C'\fR command of Perl debugger (see perldebug) one can
1498 deduce which operations are overloaded (and which ancestor triggers
1499 this overloading). Say, if \f(CW\*(C`eq\*(C'\fR is overloaded, then the method \f(CW\*(C`(eq\*(C'\fR
1500 is shown by debugger. The method \f(CW\*(C`()\*(C'\fR corresponds to the \f(CW\*(C`fallback\*(C'\fR
1501 key (in fact a presence of this method shows that this package has
1502 overloading enabled, and it is what is used by the \f(CW\*(C`Overloaded\*(C'\fR
1503 function of module \f(CW\*(C`overload\*(C'\fR).
1504 .PP
1505 The module might issue the following warnings:
1506 .IP "Odd number of arguments for overload::constant" 4
1507 .IX Item "Odd number of arguments for overload::constant"
1508 (W) The call to overload::constant contained an odd number of arguments.
1509 The arguments should come in pairs.
1510 .IP "\*(Aq%s\*(Aq is not an overloadable type" 4
1511 .IX Item "'%s' is not an overloadable type"
1512 (W) You tried to overload a constant type the overload package is unaware of.
1513 .IP "\*(Aq%s\*(Aq is not a code reference" 4
1514 .IX Item "'%s' is not a code reference"
1515 (W) The second (fourth, sixth, ...) argument of overload::constant needs
1516 to be a code reference. Either an anonymous subroutine, or a reference
1517 to a subroutine.
1518 .IP "overload arg \*(Aq%s\*(Aq is invalid" 4
1519 .IX Item "overload arg '%s' is invalid"
1520 (W) \f(CW\*(C`use overload\*(C'\fR was passed an argument it did not
1521 recognize. Did you mistype an operator?
1522 .SH "BUGS AND PITFALLS"
1523 .IX Header "BUGS AND PITFALLS"
1524 .IP \(bu 4
1525 A pitfall when fallback is TRUE and Perl resorts to a built\-in
1526 implementation of an operator is that some operators have more
1527 than one semantic, for example \f(CW\*(C`|\*(C'\fR:
1528 .Sp
1529 .Vb 5
1530 \& use overload \*(Aq0+\*(Aq => sub { $_[0]\->{n}; },
1531 \& fallback => 1;
1532 \& my $x = bless { n => 4 }, "main";
1533 \& my $y = bless { n => 8 }, "main";
1534 \& print $x | $y, "\en";
1535 .Ve
1536 .Sp
1537 You might expect this to output "12".
1538 In fact, it prints "<": the ASCII result of treating "|"
1539 as a bitwise string operator \- that is, the result of treating
1540 the operands as the strings "4" and "8" rather than numbers.
1541 The fact that numify (\f(CW\*(C`0+\*(C'\fR) is implemented but stringify
1542 (\f(CW""\fR) isn\*(Aqt makes no difference since the latter is simply
1543 autogenerated from the former.
1544 .Sp
1545 The only way to change this is to provide your own subroutine
1546 for \f(CW\*(Aq|\*(Aq\fR.
1547 .IP \(bu 4
1548 Magic autogeneration increases the potential for inadvertently
1549 creating self\-referential structures.
1550 Currently Perl will not free self\-referential
1551 structures until cycles are explicitly broken.
1552 For example,
1553 .Sp
1554 .Vb 2
1555 \& use overload \*(Aq+\*(Aq => \*(Aqadd\*(Aq;
1556 \& sub add { bless [ \e$_[0], \e$_[1] ] };
1557 .Ve
1558 .Sp
1559 is asking for trouble, since
1560 .Sp
1561 .Vb 1
1562 \& $obj += $y;
1563 .Ve
1564 .Sp
1565 will effectively become
1566 .Sp
1567 .Vb 1
1568 \& $obj = add($obj, $y, undef);
1569 .Ve
1570 .Sp
1571 with the same result as
1572 .Sp
1573 .Vb 1
1574 \& $obj = [\e$obj, \e$foo];
1575 .Ve
1576 .Sp
1577 Even if no \fIexplicit\fR assignment\-variants of operators are present in
1578 the script, they may be generated by the optimizer.
1579 For example,
1580 .Sp
1581 .Vb 1
1582 \& "obj = $obj\en"
1583 .Ve
1584 .Sp
1585 may be optimized to
1586 .Sp
1587 .Vb 1
1588 \& my $tmp = \*(Aqobj = \*(Aq . $obj; $tmp .= "\en";
1589 .Ve
1590 .IP \(bu 4
1591 The symbol table is filled with names looking like line\-noise.
1592 .IP \(bu 4
1593 This bug was fixed in Perl 5.18, but may still trip you up if you are using
1594 older versions:
1595 .Sp
1596 For the purpose of inheritance every overloaded package behaves as if
1597 \&\f(CW\*(C`fallback\*(C'\fR is present (possibly undefined). This may create
1598 interesting effects if some package is not overloaded, but inherits
1599 from two overloaded packages.
1600 .IP \(bu 4
1601 Before Perl 5.14, the relation between overloading and \fBtie()\fRing was broken.
1602 Overloading was triggered or not based on the \fIprevious\fR class of the
1603 \&\fBtie()\fRd variable.
1604 .Sp
1605 This happened because the presence of overloading was checked
1606 too early, before any \fBtie()\fRd access was attempted. If the
1607 class of the value \fBFETCH()\fRed from the tied variable does not
1608 change, a simple workaround for code that is to run on older Perl
1609 versions is to access the value (via \f(CW\*(C`() = $foo\*(C'\fR or some such)
1610 immediately after \fBtie()\fRing, so that after this call the \fIprevious\fR class
1611 coincides with the current one.
1612 .IP \(bu 4
1613 Barewords are not covered by overloaded string constants.
1614 .IP \(bu 4
1615 The range operator \f(CW\*(C`..\*(C'\fR cannot be overloaded.