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