| 1 | .\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32 |
| 2 | .\" |
| 3 | .\" Standard preamble: |
| 4 | .\" ======================================================================== |
| 5 | .de Sh \" Subsection heading |
| 6 | .br |
| 7 | .if t .Sp |
| 8 | .ne 5 |
| 9 | .PP |
| 10 | \fB\\$1\fR |
| 11 | .PP |
| 12 | .. |
| 13 | .de Sp \" Vertical space (when we can't use .PP) |
| 14 | .if t .sp .5v |
| 15 | .if n .sp |
| 16 | .. |
| 17 | .de Vb \" Begin verbatim text |
| 18 | .ft CW |
| 19 | .nf |
| 20 | .ne \\$1 |
| 21 | .. |
| 22 | .de Ve \" End verbatim text |
| 23 | .ft R |
| 24 | .fi |
| 25 | .. |
| 26 | .\" Set up some character translations and predefined strings. \*(-- will |
| 27 | .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left |
| 28 | .\" double quote, and \*(R" will give a right double quote. | will give a |
| 29 | .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to |
| 30 | .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' |
| 31 | .\" expand to `' in nroff, nothing in troff, for use with C<>. |
| 32 | .tr \(*W-|\(bv\*(Tr |
| 33 | .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' |
| 34 | .ie n \{\ |
| 35 | . ds -- \(*W- |
| 36 | . ds PI pi |
| 37 | . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch |
| 38 | . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch |
| 39 | . ds L" "" |
| 40 | . ds R" "" |
| 41 | . ds C` "" |
| 42 | . ds C' "" |
| 43 | 'br\} |
| 44 | .el\{\ |
| 45 | . ds -- \|\(em\| |
| 46 | . ds PI \(*p |
| 47 | . ds L" `` |
| 48 | . ds R" '' |
| 49 | 'br\} |
| 50 | .\" |
| 51 | .\" If the F register is turned on, we'll generate index entries on stderr for |
| 52 | .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index |
| 53 | .\" entries marked with X<> in POD. Of course, you'll have to process the |
| 54 | .\" output yourself in some meaningful fashion. |
| 55 | .if \nF \{\ |
| 56 | . de IX |
| 57 | . tm Index:\\$1\t\\n%\t"\\$2" |
| 58 | .. |
| 59 | . nr % 0 |
| 60 | . rr F |
| 61 | .\} |
| 62 | .\" |
| 63 | .\" For nroff, turn off justification. Always turn off hyphenation; it makes |
| 64 | .\" way too many mistakes in technical documents. |
| 65 | .hy 0 |
| 66 | .if n .na |
| 67 | .\" |
| 68 | .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). |
| 69 | .\" Fear. Run. Save yourself. No user-serviceable parts. |
| 70 | . \" fudge factors for nroff and troff |
| 71 | .if n \{\ |
| 72 | . ds #H 0 |
| 73 | . ds #V .8m |
| 74 | . ds #F .3m |
| 75 | . ds #[ \f1 |
| 76 | . ds #] \fP |
| 77 | .\} |
| 78 | .if t \{\ |
| 79 | . ds #H ((1u-(\\\\n(.fu%2u))*.13m) |
| 80 | . ds #V .6m |
| 81 | . ds #F 0 |
| 82 | . ds #[ \& |
| 83 | . ds #] \& |
| 84 | .\} |
| 85 | . \" simple accents for nroff and troff |
| 86 | .if n \{\ |
| 87 | . ds ' \& |
| 88 | . ds ` \& |
| 89 | . ds ^ \& |
| 90 | . ds , \& |
| 91 | . ds ~ ~ |
| 92 | . ds / |
| 93 | .\} |
| 94 | .if t \{\ |
| 95 | . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" |
| 96 | . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' |
| 97 | . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' |
| 98 | . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' |
| 99 | . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' |
| 100 | . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' |
| 101 | .\} |
| 102 | . \" troff and (daisy-wheel) nroff accents |
| 103 | .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' |
| 104 | .ds 8 \h'\*(#H'\(*b\h'-\*(#H' |
| 105 | .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] |
| 106 | .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' |
| 107 | .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' |
| 108 | .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] |
| 109 | .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] |
| 110 | .ds ae a\h'-(\w'a'u*4/10)'e |
| 111 | .ds Ae A\h'-(\w'A'u*4/10)'E |
| 112 | . \" corrections for vroff |
| 113 | .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' |
| 114 | .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' |
| 115 | . \" for low resolution devices (crt and lpr) |
| 116 | .if \n(.H>23 .if \n(.V>19 \ |
| 117 | \{\ |
| 118 | . ds : e |
| 119 | . ds 8 ss |
| 120 | . ds o a |
| 121 | . ds d- d\h'-1'\(ga |
| 122 | . ds D- D\h'-1'\(hy |
| 123 | . ds th \o'bp' |
| 124 | . ds Th \o'LP' |
| 125 | . ds ae ae |
| 126 | . ds Ae AE |
| 127 | .\} |
| 128 | .rm #[ #] #H #V #F C |
| 129 | .\" ======================================================================== |
| 130 | .\" |
| 131 | .IX Title "overload 3" |
| 132 | .TH overload 3 "2001-09-21" "perl v5.8.8" "Perl Programmers Reference Guide" |
| 133 | .SH "NAME" |
| 134 | overload \- Package for overloading Perl operations |
| 135 | .SH "SYNOPSIS" |
| 136 | .IX Header "SYNOPSIS" |
| 137 | .Vb 1 |
| 138 | \& package SomeThing; |
| 139 | .Ve |
| 140 | .PP |
| 141 | .Vb 5 |
| 142 | \& use overload |
| 143 | \& '+' => \e&myadd, |
| 144 | \& '-' => \e&mysub; |
| 145 | \& # etc |
| 146 | \& ... |
| 147 | .Ve |
| 148 | .PP |
| 149 | .Vb 7 |
| 150 | \& package main; |
| 151 | \& $a = new SomeThing 57; |
| 152 | \& $b=5+$a; |
| 153 | \& ... |
| 154 | \& if (overload::Overloaded $b) {...} |
| 155 | \& ... |
| 156 | \& $strval = overload::StrVal $b; |
| 157 | .Ve |
| 158 | .SH "DESCRIPTION" |
| 159 | .IX Header "DESCRIPTION" |
| 160 | .Sh "Declaration of overloaded functions" |
| 161 | .IX Subsection "Declaration of overloaded functions" |
| 162 | The compilation directive |
| 163 | .PP |
| 164 | .Vb 4 |
| 165 | \& package Number; |
| 166 | \& use overload |
| 167 | \& "+" => \e&add, |
| 168 | \& "*=" => "muas"; |
| 169 | .Ve |
| 170 | .PP |
| 171 | declares function \fINumber::add()\fR for addition, and method \fImuas()\fR in |
| 172 | the \*(L"class\*(R" \f(CW\*(C`Number\*(C'\fR (or one of its base classes) |
| 173 | for the assignment form \f(CW\*(C`*=\*(C'\fR of multiplication. |
| 174 | .PP |
| 175 | Arguments of this directive come in (key, value) pairs. Legal values |
| 176 | are values legal inside a \f(CW\*(C`&{ ... }\*(C'\fR call, so the name of a |
| 177 | subroutine, a reference to a subroutine, or an anonymous subroutine |
| 178 | will all work. Note that values specified as strings are |
| 179 | interpreted as methods, not subroutines. Legal keys are listed below. |
| 180 | .PP |
| 181 | The subroutine \f(CW\*(C`add\*(C'\fR will be called to execute \f(CW\*(C`$a+$b\*(C'\fR if \f(CW$a\fR |
| 182 | is a reference to an object blessed into the package \f(CW\*(C`Number\*(C'\fR, or if \f(CW$a\fR is |
| 183 | not an object from a package with defined mathemagic addition, but \f(CW$b\fR is a |
| 184 | reference to a \f(CW\*(C`Number\*(C'\fR. It can also be called in other situations, like |
| 185 | \&\f(CW\*(C`$a+=7\*(C'\fR, or \f(CW\*(C`$a++\*(C'\fR. See \*(L"\s-1MAGIC\s0 \s-1AUTOGENERATION\s0\*(R". (Mathemagical |
| 186 | methods refer to methods triggered by an overloaded mathematical |
| 187 | operator.) |
| 188 | .PP |
| 189 | Since overloading respects inheritance via the \f(CW@ISA\fR hierarchy, the |
| 190 | above declaration would also trigger overloading of \f(CW\*(C`+\*(C'\fR and \f(CW\*(C`*=\*(C'\fR in |
| 191 | all the packages which inherit from \f(CW\*(C`Number\*(C'\fR. |
| 192 | .Sh "Calling Conventions for Binary Operations" |
| 193 | .IX Subsection "Calling Conventions for Binary Operations" |
| 194 | The functions specified in the \f(CW\*(C`use overload ...\*(C'\fR directive are called |
| 195 | with three (in one particular case with four, see \*(L"Last Resort\*(R") |
| 196 | arguments. If the corresponding operation is binary, then the first |
| 197 | two arguments are the two arguments of the operation. However, due to |
| 198 | general object calling conventions, the first argument should always be |
| 199 | an object in the package, so in the situation of \f(CW\*(C`7+$a\*(C'\fR, the |
| 200 | order of the arguments is interchanged. It probably does not matter |
| 201 | when implementing the addition method, but whether the arguments |
| 202 | are reversed is vital to the subtraction method. The method can |
| 203 | query this information by examining the third argument, which can take |
| 204 | three different values: |
| 205 | .IP "\s-1FALSE\s0" 7 |
| 206 | .IX Item "FALSE" |
| 207 | the order of arguments is as in the current operation. |
| 208 | .IP "\s-1TRUE\s0" 7 |
| 209 | .IX Item "TRUE" |
| 210 | the arguments are reversed. |
| 211 | .ie n .IP """undef""" 7 |
| 212 | .el .IP "\f(CWundef\fR" 7 |
| 213 | .IX Item "undef" |
| 214 | the current operation is an assignment variant (as in |
| 215 | \&\f(CW\*(C`$a+=7\*(C'\fR), but the usual function is called instead. This additional |
| 216 | information can be used to generate some optimizations. Compare |
| 217 | \&\*(L"Calling Conventions for Mutators\*(R". |
| 218 | .Sh "Calling Conventions for Unary Operations" |
| 219 | .IX Subsection "Calling Conventions for Unary Operations" |
| 220 | Unary operation are considered binary operations with the second |
| 221 | argument being \f(CW\*(C`undef\*(C'\fR. Thus the functions that overloads \f(CW\*(C`{"++"}\*(C'\fR |
| 222 | is called with arguments \f(CW\*(C`($a,undef,'')\*(C'\fR when \f(CW$a\fR++ is executed. |
| 223 | .Sh "Calling Conventions for Mutators" |
| 224 | .IX Subsection "Calling Conventions for Mutators" |
| 225 | Two types of mutators have different calling conventions: |
| 226 | .ie n .IP """++""\fR and \f(CW""\-\-""" 4 |
| 227 | .el .IP "\f(CW++\fR and \f(CW\-\-\fR" 4 |
| 228 | .IX Item "++ and --" |
| 229 | The routines which implement these operators are expected to actually |
| 230 | \&\fImutate\fR their arguments. So, assuming that \f(CW$obj\fR is a reference to a |
| 231 | number, |
| 232 | .Sp |
| 233 | .Vb 1 |
| 234 | \& sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \e$n} |
| 235 | .Ve |
| 236 | .Sp |
| 237 | is an appropriate implementation of overloaded \f(CW\*(C`++\*(C'\fR. Note that |
| 238 | .Sp |
| 239 | .Vb 1 |
| 240 | \& sub incr { ++$ {$_[0]} ; shift } |
| 241 | .Ve |
| 242 | .Sp |
| 243 | is \s-1OK\s0 if used with preincrement and with postincrement. (In the case |
| 244 | of postincrement a copying will be performed, see \*(L"Copy Constructor\*(R".) |
| 245 | .ie n .IP """x="" and other assignment versions" 4 |
| 246 | .el .IP "\f(CWx=\fR and other assignment versions" 4 |
| 247 | .IX Item "x= and other assignment versions" |
| 248 | There is nothing special about these methods. They may change the |
| 249 | value of their arguments, and may leave it as is. The result is going |
| 250 | to be assigned to the value in the left-hand-side if different from |
| 251 | this value. |
| 252 | .Sp |
| 253 | This allows for the same method to be used as overloaded \f(CW\*(C`+=\*(C'\fR and |
| 254 | \&\f(CW\*(C`+\*(C'\fR. Note that this is \fIallowed\fR, but not recommended, since by the |
| 255 | semantic of \*(L"Fallback\*(R" Perl will call the method for \f(CW\*(C`+\*(C'\fR anyway, |
| 256 | if \f(CW\*(C`+=\*(C'\fR is not overloaded. |
| 257 | .PP |
| 258 | \&\fBWarning.\fR Due to the presence of assignment versions of operations, |
| 259 | routines which may be called in assignment context may create |
| 260 | self-referential structures. Currently Perl will not free self-referential |
| 261 | structures until cycles are \f(CW\*(C`explicitly\*(C'\fR broken. You may get problems |
| 262 | when traversing your structures too. |
| 263 | .PP |
| 264 | Say, |
| 265 | .PP |
| 266 | .Vb 1 |
| 267 | \& use overload '+' => sub { bless [ \e$_[0], \e$_[1] ] }; |
| 268 | .Ve |
| 269 | .PP |
| 270 | is asking for trouble, since for code \f(CW\*(C`$obj += $foo\*(C'\fR the subroutine |
| 271 | is called as \f(CW\*(C`$obj = add($obj, $foo, undef)\*(C'\fR, or \f(CW\*(C`$obj = [\e$obj, |
| 272 | \&\e$foo]\*(C'\fR. If using such a subroutine is an important optimization, one |
| 273 | can overload \f(CW\*(C`+=\*(C'\fR explicitly by a non\-\*(L"optimized\*(R" version, or switch |
| 274 | to non-optimized version if \f(CW\*(C`not defined $_[2]\*(C'\fR (see |
| 275 | \&\*(L"Calling Conventions for Binary Operations\*(R"). |
| 276 | .PP |
| 277 | Even if no \fIexplicit\fR assignment-variants of operators are present in |
| 278 | the script, they may be generated by the optimizer. Say, \f(CW",$obj,"\fR or |
| 279 | \&\f(CW',' . $obj . ','\fR may be both optimized to |
| 280 | .PP |
| 281 | .Vb 1 |
| 282 | \& my $tmp = ',' . $obj; $tmp .= ','; |
| 283 | .Ve |
| 284 | .Sh "Overloadable Operations" |
| 285 | .IX Subsection "Overloadable Operations" |
| 286 | The following symbols can be specified in \f(CW\*(C`use overload\*(C'\fR directive: |
| 287 | .IP "* \fIArithmetic operations\fR" 5 |
| 288 | .IX Item "Arithmetic operations" |
| 289 | .Vb 2 |
| 290 | \& "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=", |
| 291 | \& "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=", |
| 292 | .Ve |
| 293 | .Sp |
| 294 | For these operations a substituted non-assignment variant can be called if |
| 295 | the assignment variant is not available. Methods for operations \f(CW\*(C`+\*(C'\fR, |
| 296 | \&\f(CW\*(C`\-\*(C'\fR, \f(CW\*(C`+=\*(C'\fR, and \f(CW\*(C`\-=\*(C'\fR can be called to automatically generate |
| 297 | increment and decrement methods. The operation \f(CW\*(C`\-\*(C'\fR can be used to |
| 298 | autogenerate missing methods for unary minus or \f(CW\*(C`abs\*(C'\fR. |
| 299 | .Sp |
| 300 | See \*(L"\s-1MAGIC\s0 \s-1AUTOGENERATION\s0\*(R", \*(L"Calling Conventions for Mutators\*(R" and |
| 301 | \&\*(L"Calling Conventions for Binary Operations\*(R") for details of these |
| 302 | substitutions. |
| 303 | .IP "* \fIComparison operations\fR" 5 |
| 304 | .IX Item "Comparison operations" |
| 305 | .Vb 2 |
| 306 | \& "<", "<=", ">", ">=", "==", "!=", "<=>", |
| 307 | \& "lt", "le", "gt", "ge", "eq", "ne", "cmp", |
| 308 | .Ve |
| 309 | .Sp |
| 310 | If the corresponding \*(L"spaceship\*(R" variant is available, it can be |
| 311 | used to substitute for the missing operation. During \f(CW\*(C`sort\*(C'\fRing |
| 312 | arrays, \f(CW\*(C`cmp\*(C'\fR is used to compare values subject to \f(CW\*(C`use overload\*(C'\fR. |
| 313 | .IP "* \fIBit operations\fR" 5 |
| 314 | .IX Item "Bit operations" |
| 315 | .Vb 1 |
| 316 | \& "&", "^", "|", "neg", "!", "~", |
| 317 | .Ve |
| 318 | .Sp |
| 319 | \&\f(CW\*(C`neg\*(C'\fR stands for unary minus. If the method for \f(CW\*(C`neg\*(C'\fR is not |
| 320 | specified, it can be autogenerated using the method for |
| 321 | subtraction. If the method for \f(CW\*(C`!\*(C'\fR is not specified, it can be |
| 322 | autogenerated using the methods for \f(CW\*(C`bool\*(C'\fR, or \f(CW""\fR, or \f(CW\*(C`0+\*(C'\fR. |
| 323 | .IP "* \fIIncrement and decrement\fR" 5 |
| 324 | .IX Item "Increment and decrement" |
| 325 | .Vb 1 |
| 326 | \& "++", "--", |
| 327 | .Ve |
| 328 | .Sp |
| 329 | If undefined, addition and subtraction methods can be |
| 330 | used instead. These operations are called both in prefix and |
| 331 | postfix form. |
| 332 | .IP "* \fITranscendental functions\fR" 5 |
| 333 | .IX Item "Transcendental functions" |
| 334 | .Vb 1 |
| 335 | \& "atan2", "cos", "sin", "exp", "abs", "log", "sqrt", "int" |
| 336 | .Ve |
| 337 | .Sp |
| 338 | If \f(CW\*(C`abs\*(C'\fR is unavailable, it can be autogenerated using methods |
| 339 | for "<\*(L" or \*(R"<=>" combined with either unary minus or subtraction. |
| 340 | .Sp |
| 341 | Note that traditionally the Perl function int rounds to 0, thus for |
| 342 | floating-point-like types one should follow the same semantic. If |
| 343 | \&\f(CW\*(C`int\*(C'\fR is unavailable, it can be autogenerated using the overloading of |
| 344 | \&\f(CW\*(C`0+\*(C'\fR. |
| 345 | .IP "* \fIBoolean, string and numeric conversion\fR" 5 |
| 346 | .IX Item "Boolean, string and numeric conversion" |
| 347 | .Vb 1 |
| 348 | \& 'bool', '""', '0+', |
| 349 | .Ve |
| 350 | .Sp |
| 351 | If one or two of these operations are not overloaded, the remaining ones can |
| 352 | be used instead. \f(CW\*(C`bool\*(C'\fR is used in the flow control operators |
| 353 | (like \f(CW\*(C`while\*(C'\fR) and for the ternary \f(CW\*(C`?:\*(C'\fR operation. These functions can |
| 354 | return any arbitrary Perl value. If the corresponding operation for this value |
| 355 | is overloaded too, that operation will be called again with this value. |
| 356 | .Sp |
| 357 | As a special case if the overload returns the object itself then it will |
| 358 | be used directly. An overloaded conversion returning the object is |
| 359 | probably a bug, because you're likely to get something that looks like |
| 360 | \&\f(CW\*(C`YourPackage=HASH(0x8172b34)\*(C'\fR. |
| 361 | .IP "* \fIIteration\fR" 5 |
| 362 | .IX Item "Iteration" |
| 363 | .Vb 1 |
| 364 | \& "<>" |
| 365 | .Ve |
| 366 | .Sp |
| 367 | If not overloaded, the argument will be converted to a filehandle or |
| 368 | glob (which may require a stringification). The same overloading |
| 369 | happens both for the \fIread-filehandle\fR syntax \f(CW\*(C`<$var>\*(C'\fR and |
| 370 | \&\fIglobbing\fR syntax \f(CW\*(C`<${var}>\*(C'\fR. |
| 371 | .Sp |
| 372 | \&\fB\s-1BUGS\s0\fR Even in list context, the iterator is currently called only |
| 373 | once and with scalar context. |
| 374 | .IP "* \fIDereferencing\fR" 5 |
| 375 | .IX Item "Dereferencing" |
| 376 | .Vb 1 |
| 377 | \& '${}', '@{}', '%{}', '&{}', '*{}'. |
| 378 | .Ve |
| 379 | .Sp |
| 380 | If not overloaded, the argument will be dereferenced \fIas is\fR, thus |
| 381 | should be of correct type. These functions should return a reference |
| 382 | of correct type, or another object with overloaded dereferencing. |
| 383 | .Sp |
| 384 | As a special case if the overload returns the object itself then it |
| 385 | will be used directly (provided it is the correct type). |
| 386 | .Sp |
| 387 | The dereference operators must be specified explicitly they will not be passed to |
| 388 | \&\*(L"nomethod\*(R". |
| 389 | .IP "* \fISpecial\fR" 5 |
| 390 | .IX Item "Special" |
| 391 | .Vb 1 |
| 392 | \& "nomethod", "fallback", "=", |
| 393 | .Ve |
| 394 | .Sp |
| 395 | see "\s-1SPECIAL\s0 \s-1SYMBOLS\s0 \s-1FOR\s0 \f(CW\*(C`use overload\*(C'\fR". |
| 396 | .PP |
| 397 | See \*(L"Fallback\*(R" for an explanation of when a missing method can be |
| 398 | autogenerated. |
| 399 | .PP |
| 400 | A computer-readable form of the above table is available in the hash |
| 401 | \&\f(CW%overload::ops\fR, with values being space-separated lists of names: |
| 402 | .PP |
| 403 | .Vb 13 |
| 404 | \& with_assign => '+ - * / % ** << >> x .', |
| 405 | \& assign => '+= -= *= /= %= **= <<= >>= x= .=', |
| 406 | \& num_comparison => '< <= > >= == !=', |
| 407 | \& '3way_comparison'=> '<=> cmp', |
| 408 | \& str_comparison => 'lt le gt ge eq ne', |
| 409 | \& binary => '& | ^', |
| 410 | \& unary => 'neg ! ~', |
| 411 | \& mutators => '++ --', |
| 412 | \& func => 'atan2 cos sin exp abs log sqrt', |
| 413 | \& conversion => 'bool "" 0+', |
| 414 | \& iterators => '<>', |
| 415 | \& dereferencing => '${} @{} %{} &{} *{}', |
| 416 | \& special => 'nomethod fallback =' |
| 417 | .Ve |
| 418 | .Sh "Inheritance and overloading" |
| 419 | .IX Subsection "Inheritance and overloading" |
| 420 | Inheritance interacts with overloading in two ways. |
| 421 | .ie n .IP "Strings as values of ""use overload"" directive" 4 |
| 422 | .el .IP "Strings as values of \f(CWuse overload\fR directive" 4 |
| 423 | .IX Item "Strings as values of use overload directive" |
| 424 | If \f(CW\*(C`value\*(C'\fR in |
| 425 | .Sp |
| 426 | .Vb 1 |
| 427 | \& use overload key => value; |
| 428 | .Ve |
| 429 | .Sp |
| 430 | is a string, it is interpreted as a method name. |
| 431 | .IP "Overloading of an operation is inherited by derived classes" 4 |
| 432 | .IX Item "Overloading of an operation is inherited by derived classes" |
| 433 | Any class derived from an overloaded class is also overloaded. The |
| 434 | set of overloaded methods is the union of overloaded methods of all |
| 435 | the ancestors. If some method is overloaded in several ancestor, then |
| 436 | which description will be used is decided by the usual inheritance |
| 437 | rules: |
| 438 | .Sp |
| 439 | If \f(CW\*(C`A\*(C'\fR inherits from \f(CW\*(C`B\*(C'\fR and \f(CW\*(C`C\*(C'\fR (in this order), \f(CW\*(C`B\*(C'\fR overloads |
| 440 | \&\f(CW\*(C`+\*(C'\fR with \f(CW\*(C`\e&D::plus_sub\*(C'\fR, and \f(CW\*(C`C\*(C'\fR overloads \f(CW\*(C`+\*(C'\fR by \f(CW"plus_meth"\fR, |
| 441 | then the subroutine \f(CW\*(C`D::plus_sub\*(C'\fR will be called to implement |
| 442 | operation \f(CW\*(C`+\*(C'\fR for an object in package \f(CW\*(C`A\*(C'\fR. |
| 443 | .PP |
| 444 | Note that since the value of the \f(CW\*(C`fallback\*(C'\fR key is not a subroutine, |
| 445 | its inheritance is not governed by the above rules. In the current |
| 446 | implementation, the value of \f(CW\*(C`fallback\*(C'\fR in the first overloaded |
| 447 | ancestor is used, but this is accidental and subject to change. |
| 448 | .ie n .SH "SPECIAL SYMBOLS FOR ""use overload""" |
| 449 | .el .SH "SPECIAL SYMBOLS FOR \f(CWuse overload\fP" |
| 450 | .IX Header "SPECIAL SYMBOLS FOR use overload" |
| 451 | Three keys are recognized by Perl that are not covered by the above |
| 452 | description. |
| 453 | .Sh "Last Resort" |
| 454 | .IX Subsection "Last Resort" |
| 455 | \&\f(CW"nomethod"\fR should be followed by a reference to a function of four |
| 456 | parameters. If defined, it is called when the overloading mechanism |
| 457 | cannot find a method for some operation. The first three arguments of |
| 458 | this function coincide with the arguments for the corresponding method if |
| 459 | it were found, the fourth argument is the symbol |
| 460 | corresponding to the missing method. If several methods are tried, |
| 461 | the last one is used. Say, \f(CW\*(C`1\-$a\*(C'\fR can be equivalent to |
| 462 | .PP |
| 463 | .Vb 1 |
| 464 | \& &nomethodMethod($a,1,1,"-") |
| 465 | .Ve |
| 466 | .PP |
| 467 | if the pair \f(CW"nomethod" => "nomethodMethod"\fR was specified in the |
| 468 | \&\f(CW\*(C`use overload\*(C'\fR directive. |
| 469 | .PP |
| 470 | The \f(CW"nomethod"\fR mechanism is \fInot\fR used for the dereference operators |
| 471 | ( ${} @{} %{} &{} *{} ). |
| 472 | .PP |
| 473 | If some operation cannot be resolved, and there is no function |
| 474 | assigned to \f(CW"nomethod"\fR, then an exception will be raised via \fIdie()\fR\-\- |
| 475 | unless \f(CW"fallback"\fR was specified as a key in \f(CW\*(C`use overload\*(C'\fR directive. |
| 476 | .Sh "Fallback" |
| 477 | .IX Subsection "Fallback" |
| 478 | The key \f(CW"fallback"\fR governs what to do if a method for a particular |
| 479 | operation is not found. Three different cases are possible depending on |
| 480 | the value of \f(CW"fallback"\fR: |
| 481 | .ie n .IP "* ""undef""" 16 |
| 482 | .el .IP "* \f(CWundef\fR" 16 |
| 483 | .IX Item "undef" |
| 484 | Perl tries to use a |
| 485 | substituted method (see \*(L"\s-1MAGIC\s0 \s-1AUTOGENERATION\s0\*(R"). If this fails, it |
| 486 | then tries to calls \f(CW"nomethod"\fR value; if missing, an exception |
| 487 | will be raised. |
| 488 | .IP "* \s-1TRUE\s0" 16 |
| 489 | .IX Item "TRUE" |
| 490 | The same as for the \f(CW\*(C`undef\*(C'\fR value, but no exception is raised. Instead, |
| 491 | it silently reverts to what it would have done were there no \f(CW\*(C`use overload\*(C'\fR |
| 492 | present. |
| 493 | .IP "* defined, but \s-1FALSE\s0" 16 |
| 494 | .IX Item "defined, but FALSE" |
| 495 | No autogeneration is tried. Perl tries to call |
| 496 | \&\f(CW"nomethod"\fR value, and if this is missing, raises an exception. |
| 497 | .PP |
| 498 | \&\fBNote.\fR \f(CW"fallback"\fR inheritance via \f(CW@ISA\fR is not carved in stone |
| 499 | yet, see \*(L"Inheritance and overloading\*(R". |
| 500 | .Sh "Copy Constructor" |
| 501 | .IX Subsection "Copy Constructor" |
| 502 | The value for \f(CW"="\fR is a reference to a function with three |
| 503 | arguments, i.e., it looks like the other values in \f(CW\*(C`use |
| 504 | overload\*(C'\fR. However, it does not overload the Perl assignment |
| 505 | operator. This would go against Camel hair. |
| 506 | .PP |
| 507 | This operation is called in the situations when a mutator is applied |
| 508 | to a reference that shares its object with some other reference, such |
| 509 | as |
| 510 | .PP |
| 511 | .Vb 2 |
| 512 | \& $a=$b; |
| 513 | \& ++$a; |
| 514 | .Ve |
| 515 | .PP |
| 516 | To make this change \f(CW$a\fR and not change \f(CW$b\fR, a copy of \f(CW$$a\fR is made, |
| 517 | and \f(CW$a\fR is assigned a reference to this new object. This operation is |
| 518 | done during execution of the \f(CW\*(C`++$a\*(C'\fR, and not during the assignment, |
| 519 | (so before the increment \f(CW$$a\fR coincides with \f(CW$$b\fR). This is only |
| 520 | done if \f(CW\*(C`++\*(C'\fR is expressed via a method for \f(CW'++'\fR or \f(CW'+='\fR (or |
| 521 | \&\f(CW\*(C`nomethod\*(C'\fR). Note that if this operation is expressed via \f(CW'+'\fR |
| 522 | a nonmutator, i.e., as in |
| 523 | .PP |
| 524 | .Vb 2 |
| 525 | \& $a=$b; |
| 526 | \& $a=$a+1; |
| 527 | .Ve |
| 528 | .PP |
| 529 | then \f(CW$a\fR does not reference a new copy of \f(CW$$a\fR, since $$a does not |
| 530 | appear as lvalue when the above code is executed. |
| 531 | .PP |
| 532 | If the copy constructor is required during the execution of some mutator, |
| 533 | but a method for \f(CW'='\fR was not specified, it can be autogenerated as a |
| 534 | string copy if the object is a plain scalar. |
| 535 | .IP "\fBExample\fR" 5 |
| 536 | .IX Item "Example" |
| 537 | The actually executed code for |
| 538 | .Sp |
| 539 | .Vb 3 |
| 540 | \& $a=$b; |
| 541 | \& Something else which does not modify $a or $b.... |
| 542 | \& ++$a; |
| 543 | .Ve |
| 544 | .Sp |
| 545 | may be |
| 546 | .Sp |
| 547 | .Vb 4 |
| 548 | \& $a=$b; |
| 549 | \& Something else which does not modify $a or $b.... |
| 550 | \& $a = $a->clone(undef,""); |
| 551 | \& $a->incr(undef,""); |
| 552 | .Ve |
| 553 | .Sp |
| 554 | if \f(CW$b\fR was mathemagical, and \f(CW'++'\fR was overloaded with \f(CW\*(C`\e&incr\*(C'\fR, |
| 555 | \&\f(CW'='\fR was overloaded with \f(CW\*(C`\e&clone\*(C'\fR. |
| 556 | .PP |
| 557 | Same behaviour is triggered by \f(CW\*(C`$b = $a++\*(C'\fR, which is consider a synonym for |
| 558 | \&\f(CW\*(C`$b = $a; ++$a\*(C'\fR. |
| 559 | .SH "MAGIC AUTOGENERATION" |
| 560 | .IX Header "MAGIC AUTOGENERATION" |
| 561 | If a method for an operation is not found, and the value for \f(CW"fallback"\fR is |
| 562 | \&\s-1TRUE\s0 or undefined, Perl tries to autogenerate a substitute method for |
| 563 | the missing operation based on the defined operations. Autogenerated method |
| 564 | substitutions are possible for the following operations: |
| 565 | .IP "\fIAssignment forms of arithmetic operations\fR" 16 |
| 566 | .IX Item "Assignment forms of arithmetic operations" |
| 567 | \&\f(CW\*(C`$a+=$b\*(C'\fR can use the method for \f(CW"+"\fR if the method for \f(CW"+="\fR |
| 568 | is not defined. |
| 569 | .IP "\fIConversion operations\fR" 16 |
| 570 | .IX Item "Conversion operations" |
| 571 | String, numeric, and boolean conversion are calculated in terms of one |
| 572 | another if not all of them are defined. |
| 573 | .IP "\fIIncrement and decrement\fR" 16 |
| 574 | .IX Item "Increment and decrement" |
| 575 | The \f(CW\*(C`++$a\*(C'\fR operation can be expressed in terms of \f(CW\*(C`$a+=1\*(C'\fR or \f(CW\*(C`$a+1\*(C'\fR, |
| 576 | and \f(CW\*(C`$a\-\-\*(C'\fR in terms of \f(CW\*(C`$a\-=1\*(C'\fR and \f(CW\*(C`$a\-1\*(C'\fR. |
| 577 | .ie n .IP """abs($a)""" 16 |
| 578 | .el .IP "\f(CWabs($a)\fR" 16 |
| 579 | .IX Item "abs($a)" |
| 580 | can be expressed in terms of \f(CW\*(C`$a<0\*(C'\fR and \f(CW\*(C`\-$a\*(C'\fR (or \f(CW\*(C`0\-$a\*(C'\fR). |
| 581 | .IP "\fIUnary minus\fR" 16 |
| 582 | .IX Item "Unary minus" |
| 583 | can be expressed in terms of subtraction. |
| 584 | .IP "\fINegation\fR" 16 |
| 585 | .IX Item "Negation" |
| 586 | \&\f(CW\*(C`!\*(C'\fR and \f(CW\*(C`not\*(C'\fR can be expressed in terms of boolean conversion, or |
| 587 | string or numerical conversion. |
| 588 | .IP "\fIConcatenation\fR" 16 |
| 589 | .IX Item "Concatenation" |
| 590 | can be expressed in terms of string conversion. |
| 591 | .IP "\fIComparison operations\fR" 16 |
| 592 | .IX Item "Comparison operations" |
| 593 | can be expressed in terms of its \*(L"spaceship\*(R" counterpart: either |
| 594 | \&\f(CW\*(C`<=>\*(C'\fR or \f(CW\*(C`cmp\*(C'\fR: |
| 595 | .Sp |
| 596 | .Vb 2 |
| 597 | \& <, >, <=, >=, ==, != in terms of <=> |
| 598 | \& lt, gt, le, ge, eq, ne in terms of cmp |
| 599 | .Ve |
| 600 | .IP "\fIIterator\fR" 16 |
| 601 | .IX Item "Iterator" |
| 602 | .Vb 1 |
| 603 | \& <> in terms of builtin operations |
| 604 | .Ve |
| 605 | .IP "\fIDereferencing\fR" 16 |
| 606 | .IX Item "Dereferencing" |
| 607 | .Vb 1 |
| 608 | \& ${} @{} %{} &{} *{} in terms of builtin operations |
| 609 | .Ve |
| 610 | .IP "\fICopy operator\fR" 16 |
| 611 | .IX Item "Copy operator" |
| 612 | can be expressed in terms of an assignment to the dereferenced value, if this |
| 613 | value is a scalar and not a reference. |
| 614 | .SH "Losing overloading" |
| 615 | .IX Header "Losing overloading" |
| 616 | The restriction for the comparison operation is that even if, for example, |
| 617 | `\f(CW\*(C`cmp\*(C'\fR' should return a blessed reference, the autogenerated `\f(CW\*(C`lt\*(C'\fR' |
| 618 | function will produce only a standard logical value based on the |
| 619 | numerical value of the result of `\f(CW\*(C`cmp\*(C'\fR'. In particular, a working |
| 620 | numeric conversion is needed in this case (possibly expressed in terms of |
| 621 | other conversions). |
| 622 | .PP |
| 623 | Similarly, \f(CW\*(C`.=\*(C'\fR and \f(CW\*(C`x=\*(C'\fR operators lose their mathemagical properties |
| 624 | if the string conversion substitution is applied. |
| 625 | .PP |
| 626 | When you \fIchop()\fR a mathemagical object it is promoted to a string and its |
| 627 | mathemagical properties are lost. The same can happen with other |
| 628 | operations as well. |
| 629 | .SH "Run-time Overloading" |
| 630 | .IX Header "Run-time Overloading" |
| 631 | Since all \f(CW\*(C`use\*(C'\fR directives are executed at compile\-time, the only way to |
| 632 | change overloading during run-time is to |
| 633 | .PP |
| 634 | .Vb 1 |
| 635 | \& eval 'use overload "+" => \e&addmethod'; |
| 636 | .Ve |
| 637 | .PP |
| 638 | You can also use |
| 639 | .PP |
| 640 | .Vb 1 |
| 641 | \& eval 'no overload "+", "--", "<="'; |
| 642 | .Ve |
| 643 | .PP |
| 644 | though the use of these constructs during run-time is questionable. |
| 645 | .SH "Public functions" |
| 646 | .IX Header "Public functions" |
| 647 | Package \f(CW\*(C`overload.pm\*(C'\fR provides the following public functions: |
| 648 | .IP "overload::StrVal(arg)" 5 |
| 649 | .IX Item "overload::StrVal(arg)" |
| 650 | Gives string value of \f(CW\*(C`arg\*(C'\fR as in absence of stringify overloading. If you |
| 651 | are using this to get the address of a reference (useful for checking if two |
| 652 | references point to the same thing) then you may be better off using |
| 653 | \&\f(CW\*(C`Scalar::Util::refaddr()\*(C'\fR, which is faster. |
| 654 | .IP "overload::Overloaded(arg)" 5 |
| 655 | .IX Item "overload::Overloaded(arg)" |
| 656 | Returns true if \f(CW\*(C`arg\*(C'\fR is subject to overloading of some operations. |
| 657 | .IP "overload::Method(obj,op)" 5 |
| 658 | .IX Item "overload::Method(obj,op)" |
| 659 | Returns \f(CW\*(C`undef\*(C'\fR or a reference to the method that implements \f(CW\*(C`op\*(C'\fR. |
| 660 | .SH "Overloading constants" |
| 661 | .IX Header "Overloading constants" |
| 662 | For some applications, the Perl parser mangles constants too much. |
| 663 | It is possible to hook into this process via \f(CW\*(C`overload::constant()\*(C'\fR |
| 664 | and \f(CW\*(C`overload::remove_constant()\*(C'\fR functions. |
| 665 | .PP |
| 666 | These functions take a hash as an argument. The recognized keys of this hash |
| 667 | are: |
| 668 | .IP "integer" 8 |
| 669 | .IX Item "integer" |
| 670 | to overload integer constants, |
| 671 | .IP "float" 8 |
| 672 | .IX Item "float" |
| 673 | to overload floating point constants, |
| 674 | .IP "binary" 8 |
| 675 | .IX Item "binary" |
| 676 | to overload octal and hexadecimal constants, |
| 677 | .IP "q" 8 |
| 678 | .IX Item "q" |
| 679 | 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 |
| 680 | strings and here\-documents, |
| 681 | .IP "qr" 8 |
| 682 | .IX Item "qr" |
| 683 | to overload constant pieces of regular expressions. |
| 684 | .PP |
| 685 | The corresponding values are references to functions which take three arguments: |
| 686 | the first one is the \fIinitial\fR string form of the constant, the second one |
| 687 | is how Perl interprets this constant, the third one is how the constant is used. |
| 688 | Note that the initial string form does not |
| 689 | contain string delimiters, and has backslashes in backslash-delimiter |
| 690 | combinations stripped (thus the value of delimiter is not relevant for |
| 691 | processing of this string). The return value of this function is how this |
| 692 | constant is going to be interpreted by Perl. The third argument is undefined |
| 693 | 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 |
| 694 | context (comes from strings, regular expressions, and single-quote \s-1HERE\s0 |
| 695 | 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, |
| 696 | 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. |
| 697 | .PP |
| 698 | Since an expression \f(CW"ab$cd,,"\fR is just a shortcut for \f(CW'ab' . $cd . ',,'\fR, |
| 699 | it is expected that overloaded constant strings are equipped with reasonable |
| 700 | overloaded catenation operator, otherwise absurd results will result. |
| 701 | Similarly, negative numbers are considered as negations of positive constants. |
| 702 | .PP |
| 703 | Note that it is probably meaningless to call the functions \fIoverload::constant()\fR |
| 704 | and \fIoverload::remove_constant()\fR from anywhere but \fIimport()\fR and \fIunimport()\fR methods. |
| 705 | From these methods they may be called as |
| 706 | .PP |
| 707 | .Vb 6 |
| 708 | \& sub import { |
| 709 | \& shift; |
| 710 | \& return unless @_; |
| 711 | \& die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant'; |
| 712 | \& overload::constant integer => sub {Math::BigInt->new(shift)}; |
| 713 | \& } |
| 714 | .Ve |
| 715 | .PP |
| 716 | \&\fB\s-1BUGS\s0\fR Currently overloaded-ness of constants does not propagate |
| 717 | into \f(CW\*(C`eval '...'\*(C'\fR. |
| 718 | .SH "IMPLEMENTATION" |
| 719 | .IX Header "IMPLEMENTATION" |
| 720 | What follows is subject to change \s-1RSN\s0. |
| 721 | .PP |
| 722 | The table of methods for all operations is cached in magic for the |
| 723 | symbol table hash for the package. The cache is invalidated during |
| 724 | processing of \f(CW\*(C`use overload\*(C'\fR, \f(CW\*(C`no overload\*(C'\fR, new function |
| 725 | definitions, and changes in \f(CW@ISA\fR. However, this invalidation remains |
| 726 | unprocessed until the next \f(CW\*(C`bless\*(C'\fRing into the package. Hence if you |
| 727 | want to change overloading structure dynamically, you'll need an |
| 728 | additional (fake) \f(CW\*(C`bless\*(C'\fRing to update the table. |
| 729 | .PP |
| 730 | (Every SVish thing has a magic queue, and magic is an entry in that |
| 731 | queue. This is how a single variable may participate in multiple |
| 732 | forms of magic simultaneously. For instance, environment variables |
| 733 | regularly have two forms at once: their \f(CW%ENV\fR magic and their taint |
| 734 | magic. However, the magic which implements overloading is applied to |
| 735 | the stashes, which are rarely used directly, thus should not slow down |
| 736 | Perl.) |
| 737 | .PP |
| 738 | If an object belongs to a package using overload, it carries a special |
| 739 | flag. Thus the only speed penalty during arithmetic operations without |
| 740 | overloading is the checking of this flag. |
| 741 | .PP |
| 742 | In fact, if \f(CW\*(C`use overload\*(C'\fR is not present, there is almost no overhead |
| 743 | for overloadable operations, so most programs should not suffer |
| 744 | measurable performance penalties. A considerable effort was made to |
| 745 | minimize the overhead when overload is used in some package, but the |
| 746 | arguments in question do not belong to packages using overload. When |
| 747 | in doubt, test your speed with \f(CW\*(C`use overload\*(C'\fR and without it. So far |
| 748 | there have been no reports of substantial speed degradation if Perl is |
| 749 | compiled with optimization turned on. |
| 750 | .PP |
| 751 | There is no size penalty for data if overload is not used. The only |
| 752 | size penalty if overload is used in some package is that \fIall\fR the |
| 753 | packages acquire a magic during the next \f(CW\*(C`bless\*(C'\fRing into the |
| 754 | package. This magic is three-words-long for packages without |
| 755 | overloading, and carries the cache table if the package is overloaded. |
| 756 | .PP |
| 757 | Copying (\f(CW\*(C`$a=$b\*(C'\fR) is shallow; however, a one-level-deep copying is |
| 758 | carried out before any operation that can imply an assignment to the |
| 759 | object \f(CW$a\fR (or \f(CW$b\fR) refers to, like \f(CW\*(C`$a++\*(C'\fR. You can override this |
| 760 | behavior by defining your own copy constructor (see \*(L"Copy Constructor\*(R"). |
| 761 | .PP |
| 762 | It is expected that arguments to methods that are not explicitly supposed |
| 763 | to be changed are constant (but this is not enforced). |
| 764 | .SH "Metaphor clash" |
| 765 | .IX Header "Metaphor clash" |
| 766 | One may wonder why the semantic of overloaded \f(CW\*(C`=\*(C'\fR is so counter intuitive. |
| 767 | If it \fIlooks\fR counter intuitive to you, you are subject to a metaphor |
| 768 | clash. |
| 769 | .PP |
| 770 | Here is a Perl object metaphor: |
| 771 | .PP |
| 772 | \&\fI object is a reference to blessed data\fR |
| 773 | .PP |
| 774 | and an arithmetic metaphor: |
| 775 | .PP |
| 776 | \&\fI object is a thing by itself\fR. |
| 777 | .PP |
| 778 | The \fImain\fR problem of overloading \f(CW\*(C`=\*(C'\fR is the fact that these metaphors |
| 779 | imply different actions on the assignment \f(CW\*(C`$a = $b\*(C'\fR if \f(CW$a\fR and \f(CW$b\fR are |
| 780 | objects. Perl-think implies that \f(CW$a\fR becomes a reference to whatever |
| 781 | \&\f(CW$b\fR was referencing. Arithmetic-think implies that the value of \*(L"object\*(R" |
| 782 | \&\f(CW$a\fR is changed to become the value of the object \f(CW$b\fR, preserving the fact |
| 783 | that \f(CW$a\fR and \f(CW$b\fR are separate entities. |
| 784 | .PP |
| 785 | The difference is not relevant in the absence of mutators. After |
| 786 | a Perl-way assignment an operation which mutates the data referenced by \f(CW$a\fR |
| 787 | would change the data referenced by \f(CW$b\fR too. Effectively, after |
| 788 | \&\f(CW\*(C`$a = $b\*(C'\fR values of \f(CW$a\fR and \f(CW$b\fR become \fIindistinguishable\fR. |
| 789 | .PP |
| 790 | On the other hand, anyone who has used algebraic notation knows the |
| 791 | expressive power of the arithmetic metaphor. Overloading works hard |
| 792 | to enable this metaphor while preserving the Perlian way as far as |
| 793 | possible. Since it is not possible to freely mix two contradicting |
| 794 | metaphors, overloading allows the arithmetic way to write things \fIas |
| 795 | far as all the mutators are called via overloaded access only\fR. The |
| 796 | way it is done is described in \*(L"Copy Constructor\*(R". |
| 797 | .PP |
| 798 | If some mutator methods are directly applied to the overloaded values, |
| 799 | one may need to \fIexplicitly unlink\fR other values which references the |
| 800 | same value: |
| 801 | .PP |
| 802 | .Vb 6 |
| 803 | \& $a = new Data 23; |
| 804 | \& ... |
| 805 | \& $b = $a; # $b is "linked" to $a |
| 806 | \& ... |
| 807 | \& $a = $a->clone; # Unlink $b from $a |
| 808 | \& $a->increment_by(4); |
| 809 | .Ve |
| 810 | .PP |
| 811 | Note that overloaded access makes this transparent: |
| 812 | .PP |
| 813 | .Vb 3 |
| 814 | \& $a = new Data 23; |
| 815 | \& $b = $a; # $b is "linked" to $a |
| 816 | \& $a += 4; # would unlink $b automagically |
| 817 | .Ve |
| 818 | .PP |
| 819 | However, it would not make |
| 820 | .PP |
| 821 | .Vb 2 |
| 822 | \& $a = new Data 23; |
| 823 | \& $a = 4; # Now $a is a plain 4, not 'Data' |
| 824 | .Ve |
| 825 | .PP |
| 826 | preserve \*(L"objectness\*(R" of \f(CW$a\fR. But Perl \fIhas\fR a way to make assignments |
| 827 | to an object do whatever you want. It is just not the overload, but |
| 828 | \&\fItie()\fRing interface (see \*(L"tie\*(R" in perlfunc). Adding a \s-1\fIFETCH\s0()\fR method |
| 829 | which returns the object itself, and \s-1\fISTORE\s0()\fR method which changes the |
| 830 | value of the object, one can reproduce the arithmetic metaphor in its |
| 831 | completeness, at least for variables which were \fItie()\fRd from the start. |
| 832 | .PP |
| 833 | (Note that a workaround for a bug may be needed, see \*(L"\s-1BUGS\s0\*(R".) |
| 834 | .SH "Cookbook" |
| 835 | .IX Header "Cookbook" |
| 836 | Please add examples to what follows! |
| 837 | .Sh "Two-face scalars" |
| 838 | .IX Subsection "Two-face scalars" |
| 839 | Put this in \fItwo_face.pm\fR in your Perl library directory: |
| 840 | .PP |
| 841 | .Vb 6 |
| 842 | \& package two_face; # Scalars with separate string and |
| 843 | \& # numeric values. |
| 844 | \& sub new { my $p = shift; bless [@_], $p } |
| 845 | \& use overload '""' => \e&str, '0+' => \e&num, fallback => 1; |
| 846 | \& sub num {shift->[1]} |
| 847 | \& sub str {shift->[0]} |
| 848 | .Ve |
| 849 | .PP |
| 850 | Use it as follows: |
| 851 | .PP |
| 852 | .Vb 4 |
| 853 | \& require two_face; |
| 854 | \& my $seven = new two_face ("vii", 7); |
| 855 | \& printf "seven=$seven, seven=%d, eight=%d\en", $seven, $seven+1; |
| 856 | \& print "seven contains `i'\en" if $seven =~ /i/; |
| 857 | .Ve |
| 858 | .PP |
| 859 | (The second line creates a scalar which has both a string value, and a |
| 860 | numeric value.) This prints: |
| 861 | .PP |
| 862 | .Vb 2 |
| 863 | \& seven=vii, seven=7, eight=8 |
| 864 | \& seven contains `i' |
| 865 | .Ve |
| 866 | .Sh "Two-face references" |
| 867 | .IX Subsection "Two-face references" |
| 868 | Suppose you want to create an object which is accessible as both an |
| 869 | array reference and a hash reference, similar to the |
| 870 | pseudo-hash |
| 871 | builtin Perl type. Let's make it better than a pseudo-hash by |
| 872 | allowing index 0 to be treated as a normal element. |
| 873 | .PP |
| 874 | .Vb 12 |
| 875 | \& package two_refs; |
| 876 | \& use overload '%{}' => \e&gethash, '@{}' => sub { $ {shift()} }; |
| 877 | \& sub new { |
| 878 | \& my $p = shift; |
| 879 | \& bless \e [@_], $p; |
| 880 | \& } |
| 881 | \& sub gethash { |
| 882 | \& my %h; |
| 883 | \& my $self = shift; |
| 884 | \& tie %h, ref $self, $self; |
| 885 | \& \e%h; |
| 886 | \& } |
| 887 | .Ve |
| 888 | .PP |
| 889 | .Vb 16 |
| 890 | \& sub TIEHASH { my $p = shift; bless \e shift, $p } |
| 891 | \& my %fields; |
| 892 | \& my $i = 0; |
| 893 | \& $fields{$_} = $i++ foreach qw{zero one two three}; |
| 894 | \& sub STORE { |
| 895 | \& my $self = ${shift()}; |
| 896 | \& my $key = $fields{shift()}; |
| 897 | \& defined $key or die "Out of band access"; |
| 898 | \& $$self->[$key] = shift; |
| 899 | \& } |
| 900 | \& sub FETCH { |
| 901 | \& my $self = ${shift()}; |
| 902 | \& my $key = $fields{shift()}; |
| 903 | \& defined $key or die "Out of band access"; |
| 904 | \& $$self->[$key]; |
| 905 | \& } |
| 906 | .Ve |
| 907 | .PP |
| 908 | Now one can access an object using both the array and hash syntax: |
| 909 | .PP |
| 910 | .Vb 3 |
| 911 | \& my $bar = new two_refs 3,4,5,6; |
| 912 | \& $bar->[2] = 11; |
| 913 | \& $bar->{two} == 11 or die 'bad hash fetch'; |
| 914 | .Ve |
| 915 | .PP |
| 916 | Note several important features of this example. First of all, the |
| 917 | \&\fIactual\fR type of \f(CW$bar\fR is a scalar reference, and we do not overload |
| 918 | the scalar dereference. Thus we can get the \fIactual\fR non-overloaded |
| 919 | contents of \f(CW$bar\fR by just using \f(CW$$bar\fR (what we do in functions which |
| 920 | overload dereference). Similarly, the object returned by the |
| 921 | \&\s-1\fITIEHASH\s0()\fR method is a scalar reference. |
| 922 | .PP |
| 923 | Second, we create a new tied hash each time the hash syntax is used. |
| 924 | This allows us not to worry about a possibility of a reference loop, |
| 925 | which would lead to a memory leak. |
| 926 | .PP |
| 927 | Both these problems can be cured. Say, if we want to overload hash |
| 928 | dereference on a reference to an object which is \fIimplemented\fR as a |
| 929 | hash itself, the only problem one has to circumvent is how to access |
| 930 | this \fIactual\fR hash (as opposed to the \fIvirtual\fR hash exhibited by the |
| 931 | overloaded dereference operator). Here is one possible fetching routine: |
| 932 | .PP |
| 933 | .Vb 8 |
| 934 | \& sub access_hash { |
| 935 | \& my ($self, $key) = (shift, shift); |
| 936 | \& my $class = ref $self; |
| 937 | \& bless $self, 'overload::dummy'; # Disable overloading of %{} |
| 938 | \& my $out = $self->{$key}; |
| 939 | \& bless $self, $class; # Restore overloading |
| 940 | \& $out; |
| 941 | \& } |
| 942 | .Ve |
| 943 | .PP |
| 944 | To remove creation of the tied hash on each access, one may an extra |
| 945 | level of indirection which allows a non-circular structure of references: |
| 946 | .PP |
| 947 | .Vb 16 |
| 948 | \& package two_refs1; |
| 949 | \& use overload '%{}' => sub { ${shift()}->[1] }, |
| 950 | \& '@{}' => sub { ${shift()}->[0] }; |
| 951 | \& sub new { |
| 952 | \& my $p = shift; |
| 953 | \& my $a = [@_]; |
| 954 | \& my %h; |
| 955 | \& tie %h, $p, $a; |
| 956 | \& bless \e [$a, \e%h], $p; |
| 957 | \& } |
| 958 | \& sub gethash { |
| 959 | \& my %h; |
| 960 | \& my $self = shift; |
| 961 | \& tie %h, ref $self, $self; |
| 962 | \& \e%h; |
| 963 | \& } |
| 964 | .Ve |
| 965 | .PP |
| 966 | .Vb 16 |
| 967 | \& sub TIEHASH { my $p = shift; bless \e shift, $p } |
| 968 | \& my %fields; |
| 969 | \& my $i = 0; |
| 970 | \& $fields{$_} = $i++ foreach qw{zero one two three}; |
| 971 | \& sub STORE { |
| 972 | \& my $a = ${shift()}; |
| 973 | \& my $key = $fields{shift()}; |
| 974 | \& defined $key or die "Out of band access"; |
| 975 | \& $a->[$key] = shift; |
| 976 | \& } |
| 977 | \& sub FETCH { |
| 978 | \& my $a = ${shift()}; |
| 979 | \& my $key = $fields{shift()}; |
| 980 | \& defined $key or die "Out of band access"; |
| 981 | \& $a->[$key]; |
| 982 | \& } |
| 983 | .Ve |
| 984 | .PP |
| 985 | Now if \f(CW$baz\fR is overloaded like this, then \f(CW$baz\fR is a reference to a |
| 986 | reference to the intermediate array, which keeps a reference to an |
| 987 | actual array, and the access hash. The \fItie()\fRing object for the access |
| 988 | hash is a reference to a reference to the actual array, so |
| 989 | .IP "\(bu" 4 |
| 990 | There are no loops of references. |
| 991 | .IP "\(bu" 4 |
| 992 | Both \*(L"objects\*(R" which are blessed into the class \f(CW\*(C`two_refs1\*(C'\fR are |
| 993 | references to a reference to an array, thus references to a \fIscalar\fR. |
| 994 | Thus the accessor expression \f(CW\*(C`$$foo\->[$ind]\*(C'\fR involves no |
| 995 | overloaded operations. |
| 996 | .Sh "Symbolic calculator" |
| 997 | .IX Subsection "Symbolic calculator" |
| 998 | Put this in \fIsymbolic.pm\fR in your Perl library directory: |
| 999 | .PP |
| 1000 | .Vb 2 |
| 1001 | \& package symbolic; # Primitive symbolic calculator |
| 1002 | \& use overload nomethod => \e&wrap; |
| 1003 | .Ve |
| 1004 | .PP |
| 1005 | .Vb 6 |
| 1006 | \& sub new { shift; bless ['n', @_] } |
| 1007 | \& sub wrap { |
| 1008 | \& my ($obj, $other, $inv, $meth) = @_; |
| 1009 | \& ($obj, $other) = ($other, $obj) if $inv; |
| 1010 | \& bless [$meth, $obj, $other]; |
| 1011 | \& } |
| 1012 | .Ve |
| 1013 | .PP |
| 1014 | This module is very unusual as overloaded modules go: it does not |
| 1015 | provide any usual overloaded operators, instead it provides the \*(L"Last Resort\*(R" operator \f(CW\*(C`nomethod\*(C'\fR. In this example the corresponding |
| 1016 | subroutine returns an object which encapsulates operations done over |
| 1017 | the objects: \f(CW\*(C`new symbolic 3\*(C'\fR contains \f(CW\*(C`['n', 3]\*(C'\fR, \f(CW\*(C`2 + new |
| 1018 | symbolic 3\*(C'\fR contains \f(CW\*(C`['+', 2, ['n', 3]]\*(C'\fR. |
| 1019 | .PP |
| 1020 | Here is an example of the script which \*(L"calculates\*(R" the side of |
| 1021 | circumscribed octagon using the above package: |
| 1022 | .PP |
| 1023 | .Vb 4 |
| 1024 | \& require symbolic; |
| 1025 | \& my $iter = 1; # 2**($iter+2) = 8 |
| 1026 | \& my $side = new symbolic 1; |
| 1027 | \& my $cnt = $iter; |
| 1028 | .Ve |
| 1029 | .PP |
| 1030 | .Vb 4 |
| 1031 | \& while ($cnt--) { |
| 1032 | \& $side = (sqrt(1 + $side**2) - 1)/$side; |
| 1033 | \& } |
| 1034 | \& print "OK\en"; |
| 1035 | .Ve |
| 1036 | .PP |
| 1037 | The value of \f(CW$side\fR is |
| 1038 | .PP |
| 1039 | .Vb 2 |
| 1040 | \& ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]], |
| 1041 | \& undef], 1], ['n', 1]] |
| 1042 | .Ve |
| 1043 | .PP |
| 1044 | Note that while we obtained this value using a nice little script, |
| 1045 | there is no simple way to \fIuse\fR this value. In fact this value may |
| 1046 | be inspected in debugger (see perldebug), but ony if |
| 1047 | \&\f(CW\*(C`bareStringify\*(C'\fR \fBO\fRption is set, and not via \f(CW\*(C`p\*(C'\fR command. |
| 1048 | .PP |
| 1049 | If one attempts to print this value, then the overloaded operator |
| 1050 | \&\f(CW""\fR will be called, which will call \f(CW\*(C`nomethod\*(C'\fR operator. The |
| 1051 | result of this operator will be stringified again, but this result is |
| 1052 | again of type \f(CW\*(C`symbolic\*(C'\fR, which will lead to an infinite loop. |
| 1053 | .PP |
| 1054 | Add a pretty-printer method to the module \fIsymbolic.pm\fR: |
| 1055 | .PP |
| 1056 | .Vb 8 |
| 1057 | \& sub pretty { |
| 1058 | \& my ($meth, $a, $b) = @{+shift}; |
| 1059 | \& $a = 'u' unless defined $a; |
| 1060 | \& $b = 'u' unless defined $b; |
| 1061 | \& $a = $a->pretty if ref $a; |
| 1062 | \& $b = $b->pretty if ref $b; |
| 1063 | \& "[$meth $a $b]"; |
| 1064 | \& } |
| 1065 | .Ve |
| 1066 | .PP |
| 1067 | Now one can finish the script by |
| 1068 | .PP |
| 1069 | .Vb 1 |
| 1070 | \& print "side = ", $side->pretty, "\en"; |
| 1071 | .Ve |
| 1072 | .PP |
| 1073 | The method \f(CW\*(C`pretty\*(C'\fR is doing object-to-string conversion, so it |
| 1074 | is natural to overload the operator \f(CW""\fR using this method. However, |
| 1075 | inside such a method it is not necessary to pretty-print the |
| 1076 | \&\fIcomponents\fR \f(CW$a\fR and \f(CW$b\fR of an object. In the above subroutine |
| 1077 | \&\f(CW"[$meth $a $b]"\fR is a catenation of some strings and components \f(CW$a\fR |
| 1078 | and \f(CW$b\fR. If these components use overloading, the catenation operator |
| 1079 | will look for an overloaded operator \f(CW\*(C`.\*(C'\fR; if not present, it will |
| 1080 | look for an overloaded operator \f(CW""\fR. Thus it is enough to use |
| 1081 | .PP |
| 1082 | .Vb 7 |
| 1083 | \& use overload nomethod => \e&wrap, '""' => \e&str; |
| 1084 | \& sub str { |
| 1085 | \& my ($meth, $a, $b) = @{+shift}; |
| 1086 | \& $a = 'u' unless defined $a; |
| 1087 | \& $b = 'u' unless defined $b; |
| 1088 | \& "[$meth $a $b]"; |
| 1089 | \& } |
| 1090 | .Ve |
| 1091 | .PP |
| 1092 | Now one can change the last line of the script to |
| 1093 | .PP |
| 1094 | .Vb 1 |
| 1095 | \& print "side = $side\en"; |
| 1096 | .Ve |
| 1097 | .PP |
| 1098 | which outputs |
| 1099 | .PP |
| 1100 | .Vb 1 |
| 1101 | \& side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]] |
| 1102 | .Ve |
| 1103 | .PP |
| 1104 | and one can inspect the value in debugger using all the possible |
| 1105 | methods. |
| 1106 | .PP |
| 1107 | Something is still amiss: consider the loop variable \f(CW$cnt\fR of the |
| 1108 | script. It was a number, not an object. We cannot make this value of |
| 1109 | type \f(CW\*(C`symbolic\*(C'\fR, since then the loop will not terminate. |
| 1110 | .PP |
| 1111 | Indeed, to terminate the cycle, the \f(CW$cnt\fR should become false. |
| 1112 | However, the operator \f(CW\*(C`bool\*(C'\fR for checking falsity is overloaded (this |
| 1113 | time via overloaded \f(CW""\fR), and returns a long string, thus any object |
| 1114 | of type \f(CW\*(C`symbolic\*(C'\fR is true. To overcome this, we need a way to |
| 1115 | compare an object to 0. In fact, it is easier to write a numeric |
| 1116 | conversion routine. |
| 1117 | .PP |
| 1118 | Here is the text of \fIsymbolic.pm\fR with such a routine added (and |
| 1119 | slightly modified \fIstr()\fR): |
| 1120 | .PP |
| 1121 | .Vb 3 |
| 1122 | \& package symbolic; # Primitive symbolic calculator |
| 1123 | \& use overload |
| 1124 | \& nomethod => \e&wrap, '""' => \e&str, '0+' => \e# |
| 1125 | .Ve |
| 1126 | .PP |
| 1127 | .Vb 31 |
| 1128 | \& sub new { shift; bless ['n', @_] } |
| 1129 | \& sub wrap { |
| 1130 | \& my ($obj, $other, $inv, $meth) = @_; |
| 1131 | \& ($obj, $other) = ($other, $obj) if $inv; |
| 1132 | \& bless [$meth, $obj, $other]; |
| 1133 | \& } |
| 1134 | \& sub str { |
| 1135 | \& my ($meth, $a, $b) = @{+shift}; |
| 1136 | \& $a = 'u' unless defined $a; |
| 1137 | \& if (defined $b) { |
| 1138 | \& "[$meth $a $b]"; |
| 1139 | \& } else { |
| 1140 | \& "[$meth $a]"; |
| 1141 | \& } |
| 1142 | \& } |
| 1143 | \& my %subr = ( n => sub {$_[0]}, |
| 1144 | \& sqrt => sub {sqrt $_[0]}, |
| 1145 | \& '-' => sub {shift() - shift()}, |
| 1146 | \& '+' => sub {shift() + shift()}, |
| 1147 | \& '/' => sub {shift() / shift()}, |
| 1148 | \& '*' => sub {shift() * shift()}, |
| 1149 | \& '**' => sub {shift() ** shift()}, |
| 1150 | \& ); |
| 1151 | \& sub num { |
| 1152 | \& my ($meth, $a, $b) = @{+shift}; |
| 1153 | \& my $subr = $subr{$meth} |
| 1154 | \& or die "Do not know how to ($meth) in symbolic"; |
| 1155 | \& $a = $a->num if ref $a eq __PACKAGE__; |
| 1156 | \& $b = $b->num if ref $b eq __PACKAGE__; |
| 1157 | \& $subr->($a,$b); |
| 1158 | \& } |
| 1159 | .Ve |
| 1160 | .PP |
| 1161 | All the work of numeric conversion is done in \f(CW%subr\fR and \fInum()\fR. Of |
| 1162 | course, \f(CW%subr\fR is not complete, it contains only operators used in the |
| 1163 | example below. Here is the extra-credit question: why do we need an |
| 1164 | explicit recursion in \fInum()\fR? (Answer is at the end of this section.) |
| 1165 | .PP |
| 1166 | Use this module like this: |
| 1167 | .PP |
| 1168 | .Vb 4 |
| 1169 | \& require symbolic; |
| 1170 | \& my $iter = new symbolic 2; # 16-gon |
| 1171 | \& my $side = new symbolic 1; |
| 1172 | \& my $cnt = $iter; |
| 1173 | .Ve |
| 1174 | .PP |
| 1175 | .Vb 6 |
| 1176 | \& while ($cnt) { |
| 1177 | \& $cnt = $cnt - 1; # Mutator `--' not implemented |
| 1178 | \& $side = (sqrt(1 + $side**2) - 1)/$side; |
| 1179 | \& } |
| 1180 | \& printf "%s=%f\en", $side, $side; |
| 1181 | \& printf "pi=%f\en", $side*(2**($iter+2)); |
| 1182 | .Ve |
| 1183 | .PP |
| 1184 | It prints (without so many line breaks) |
| 1185 | .PP |
| 1186 | .Vb 4 |
| 1187 | \& [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] |
| 1188 | \& [n 1]] 2]]] 1] |
| 1189 | \& [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912 |
| 1190 | \& pi=3.182598 |
| 1191 | .Ve |
| 1192 | .PP |
| 1193 | The above module is very primitive. It does not implement |
| 1194 | mutator methods (\f(CW\*(C`++\*(C'\fR, \f(CW\*(C`\-=\*(C'\fR and so on), does not do deep copying |
| 1195 | (not required without mutators!), and implements only those arithmetic |
| 1196 | operations which are used in the example. |
| 1197 | .PP |
| 1198 | To implement most arithmetic operations is easy; one should just use |
| 1199 | the tables of operations, and change the code which fills \f(CW%subr\fR to |
| 1200 | .PP |
| 1201 | .Vb 12 |
| 1202 | \& my %subr = ( 'n' => sub {$_[0]} ); |
| 1203 | \& foreach my $op (split " ", $overload::ops{with_assign}) { |
| 1204 | \& $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}"; |
| 1205 | \& } |
| 1206 | \& my @bins = qw(binary 3way_comparison num_comparison str_comparison); |
| 1207 | \& foreach my $op (split " ", "@overload::ops{ @bins }") { |
| 1208 | \& $subr{$op} = eval "sub {shift() $op shift()}"; |
| 1209 | \& } |
| 1210 | \& foreach my $op (split " ", "@overload::ops{qw(unary func)}") { |
| 1211 | \& print "defining `$op'\en"; |
| 1212 | \& $subr{$op} = eval "sub {$op shift()}"; |
| 1213 | \& } |
| 1214 | .Ve |
| 1215 | .PP |
| 1216 | Due to \*(L"Calling Conventions for Mutators\*(R", we do not need anything |
| 1217 | special to make \f(CW\*(C`+=\*(C'\fR and friends work, except filling \f(CW\*(C`+=\*(C'\fR entry of |
| 1218 | \&\f(CW%subr\fR, and defining a copy constructor (needed since Perl has no |
| 1219 | way to know that the implementation of \f(CW'+='\fR does not mutate |
| 1220 | the argument, compare \*(L"Copy Constructor\*(R"). |
| 1221 | .PP |
| 1222 | To implement a copy constructor, add \f(CW\*(C`'=' => \e&cpy\*(C'\fR to \f(CW\*(C`use overload\*(C'\fR |
| 1223 | line, and code (this code assumes that mutators change things one level |
| 1224 | deep only, so recursive copying is not needed): |
| 1225 | .PP |
| 1226 | .Vb 4 |
| 1227 | \& sub cpy { |
| 1228 | \& my $self = shift; |
| 1229 | \& bless [@$self], ref $self; |
| 1230 | \& } |
| 1231 | .Ve |
| 1232 | .PP |
| 1233 | To make \f(CW\*(C`++\*(C'\fR and \f(CW\*(C`\-\-\*(C'\fR work, we need to implement actual mutators, |
| 1234 | either directly, or in \f(CW\*(C`nomethod\*(C'\fR. We continue to do things inside |
| 1235 | \&\f(CW\*(C`nomethod\*(C'\fR, thus add |
| 1236 | .PP |
| 1237 | .Vb 4 |
| 1238 | \& if ($meth eq '++' or $meth eq '--') { |
| 1239 | \& @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference |
| 1240 | \& return $obj; |
| 1241 | \& } |
| 1242 | .Ve |
| 1243 | .PP |
| 1244 | after the first line of \fIwrap()\fR. This is not a most effective |
| 1245 | implementation, one may consider |
| 1246 | .PP |
| 1247 | .Vb 1 |
| 1248 | \& sub inc { $_[0] = bless ['++', shift, 1]; } |
| 1249 | .Ve |
| 1250 | .PP |
| 1251 | instead. |
| 1252 | .PP |
| 1253 | As a final remark, note that one can fill \f(CW%subr\fR by |
| 1254 | .PP |
| 1255 | .Vb 13 |
| 1256 | \& my %subr = ( 'n' => sub {$_[0]} ); |
| 1257 | \& foreach my $op (split " ", $overload::ops{with_assign}) { |
| 1258 | \& $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}"; |
| 1259 | \& } |
| 1260 | \& my @bins = qw(binary 3way_comparison num_comparison str_comparison); |
| 1261 | \& foreach my $op (split " ", "@overload::ops{ @bins }") { |
| 1262 | \& $subr{$op} = eval "sub {shift() $op shift()}"; |
| 1263 | \& } |
| 1264 | \& foreach my $op (split " ", "@overload::ops{qw(unary func)}") { |
| 1265 | \& $subr{$op} = eval "sub {$op shift()}"; |
| 1266 | \& } |
| 1267 | \& $subr{'++'} = $subr{'+'}; |
| 1268 | \& $subr{'--'} = $subr{'-'}; |
| 1269 | .Ve |
| 1270 | .PP |
| 1271 | This finishes implementation of a primitive symbolic calculator in |
| 1272 | 50 lines of Perl code. Since the numeric values of subexpressions |
| 1273 | are not cached, the calculator is very slow. |
| 1274 | .PP |
| 1275 | Here is the answer for the exercise: In the case of \fIstr()\fR, we need no |
| 1276 | explicit recursion since the overloaded \f(CW\*(C`.\*(C'\fR\-operator will fall back |
| 1277 | to an existing overloaded operator \f(CW""\fR. Overloaded arithmetic |
| 1278 | operators \fIdo not\fR fall back to numeric conversion if \f(CW\*(C`fallback\*(C'\fR is |
| 1279 | not explicitly requested. Thus without an explicit recursion \fInum()\fR |
| 1280 | would convert \f(CW\*(C`['+', $a, $b]\*(C'\fR to \f(CW\*(C`$a + $b\*(C'\fR, which would just rebuild |
| 1281 | the argument of \fInum()\fR. |
| 1282 | .PP |
| 1283 | If you wonder why defaults for conversion are different for \fIstr()\fR and |
| 1284 | \&\fInum()\fR, note how easy it was to write the symbolic calculator. This |
| 1285 | simplicity is due to an appropriate choice of defaults. One extra |
| 1286 | note: due to the explicit recursion \fInum()\fR is more fragile than \fIsym()\fR: |
| 1287 | we need to explicitly check for the type of \f(CW$a\fR and \f(CW$b\fR. If components |
| 1288 | \&\f(CW$a\fR and \f(CW$b\fR happen to be of some related type, this may lead to problems. |
| 1289 | .Sh "\fIReally\fP symbolic calculator" |
| 1290 | .IX Subsection "Really symbolic calculator" |
| 1291 | One may wonder why we call the above calculator symbolic. The reason |
| 1292 | is that the actual calculation of the value of expression is postponed |
| 1293 | until the value is \fIused\fR. |
| 1294 | .PP |
| 1295 | To see it in action, add a method |
| 1296 | .PP |
| 1297 | .Vb 5 |
| 1298 | \& sub STORE { |
| 1299 | \& my $obj = shift; |
| 1300 | \& $#$obj = 1; |
| 1301 | \& @$obj->[0,1] = ('=', shift); |
| 1302 | \& } |
| 1303 | .Ve |
| 1304 | .PP |
| 1305 | to the package \f(CW\*(C`symbolic\*(C'\fR. After this change one can do |
| 1306 | .PP |
| 1307 | .Vb 3 |
| 1308 | \& my $a = new symbolic 3; |
| 1309 | \& my $b = new symbolic 4; |
| 1310 | \& my $c = sqrt($a**2 + $b**2); |
| 1311 | .Ve |
| 1312 | .PP |
| 1313 | and the numeric value of \f(CW$c\fR becomes 5. However, after calling |
| 1314 | .PP |
| 1315 | .Vb 1 |
| 1316 | \& $a->STORE(12); $b->STORE(5); |
| 1317 | .Ve |
| 1318 | .PP |
| 1319 | the numeric value of \f(CW$c\fR becomes 13. There is no doubt now that the module |
| 1320 | symbolic provides a \fIsymbolic\fR calculator indeed. |
| 1321 | .PP |
| 1322 | To hide the rough edges under the hood, provide a \fItie()\fRd interface to the |
| 1323 | package \f(CW\*(C`symbolic\*(C'\fR (compare with \*(L"Metaphor clash\*(R"). Add methods |
| 1324 | .PP |
| 1325 | .Vb 3 |
| 1326 | \& sub TIESCALAR { my $pack = shift; $pack->new(@_) } |
| 1327 | \& sub FETCH { shift } |
| 1328 | \& sub nop { } # Around a bug |
| 1329 | .Ve |
| 1330 | .PP |
| 1331 | (the bug is described in \*(L"\s-1BUGS\s0\*(R"). One can use this new interface as |
| 1332 | .PP |
| 1333 | .Vb 3 |
| 1334 | \& tie $a, 'symbolic', 3; |
| 1335 | \& tie $b, 'symbolic', 4; |
| 1336 | \& $a->nop; $b->nop; # Around a bug |
| 1337 | .Ve |
| 1338 | .PP |
| 1339 | .Vb 1 |
| 1340 | \& my $c = sqrt($a**2 + $b**2); |
| 1341 | .Ve |
| 1342 | .PP |
| 1343 | Now numeric value of \f(CW$c\fR is 5. After \f(CW\*(C`$a = 12; $b = 5\*(C'\fR the numeric value |
| 1344 | of \f(CW$c\fR becomes 13. To insulate the user of the module add a method |
| 1345 | .PP |
| 1346 | .Vb 1 |
| 1347 | \& sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; } |
| 1348 | .Ve |
| 1349 | .PP |
| 1350 | Now |
| 1351 | .PP |
| 1352 | .Vb 3 |
| 1353 | \& my ($a, $b); |
| 1354 | \& symbolic->vars($a, $b); |
| 1355 | \& my $c = sqrt($a**2 + $b**2); |
| 1356 | .Ve |
| 1357 | .PP |
| 1358 | .Vb 2 |
| 1359 | \& $a = 3; $b = 4; |
| 1360 | \& printf "c5 %s=%f\en", $c, $c; |
| 1361 | .Ve |
| 1362 | .PP |
| 1363 | .Vb 2 |
| 1364 | \& $a = 12; $b = 5; |
| 1365 | \& printf "c13 %s=%f\en", $c, $c; |
| 1366 | .Ve |
| 1367 | .PP |
| 1368 | shows that the numeric value of \f(CW$c\fR follows changes to the values of \f(CW$a\fR |
| 1369 | and \f(CW$b\fR. |
| 1370 | .SH "AUTHOR" |
| 1371 | .IX Header "AUTHOR" |
| 1372 | Ilya Zakharevich <\fIilya@math.mps.ohio\-state.edu\fR>. |
| 1373 | .SH "DIAGNOSTICS" |
| 1374 | .IX Header "DIAGNOSTICS" |
| 1375 | When Perl is run with the \fB\-Do\fR switch or its equivalent, overloading |
| 1376 | induces diagnostic messages. |
| 1377 | .PP |
| 1378 | Using the \f(CW\*(C`m\*(C'\fR command of Perl debugger (see perldebug) one can |
| 1379 | deduce which operations are overloaded (and which ancestor triggers |
| 1380 | this overloading). Say, if \f(CW\*(C`eq\*(C'\fR is overloaded, then the method \f(CW\*(C`(eq\*(C'\fR |
| 1381 | is shown by debugger. The method \f(CW\*(C`()\*(C'\fR corresponds to the \f(CW\*(C`fallback\*(C'\fR |
| 1382 | key (in fact a presence of this method shows that this package has |
| 1383 | overloading enabled, and it is what is used by the \f(CW\*(C`Overloaded\*(C'\fR |
| 1384 | function of module \f(CW\*(C`overload\*(C'\fR). |
| 1385 | .PP |
| 1386 | The module might issue the following warnings: |
| 1387 | .IP "Odd number of arguments for overload::constant" 4 |
| 1388 | .IX Item "Odd number of arguments for overload::constant" |
| 1389 | (W) The call to overload::constant contained an odd number of arguments. |
| 1390 | The arguments should come in pairs. |
| 1391 | .IP "`%s' is not an overloadable type" 4 |
| 1392 | .IX Item "`%s' is not an overloadable type" |
| 1393 | (W) You tried to overload a constant type the overload package is unaware of. |
| 1394 | .IP "`%s' is not a code reference" 4 |
| 1395 | .IX Item "`%s' is not a code reference" |
| 1396 | (W) The second (fourth, sixth, ...) argument of overload::constant needs |
| 1397 | to be a code reference. Either an anonymous subroutine, or a reference |
| 1398 | to a subroutine. |
| 1399 | .SH "BUGS" |
| 1400 | .IX Header "BUGS" |
| 1401 | Because it is used for overloading, the per-package hash \f(CW%OVERLOAD\fR now |
| 1402 | has a special meaning in Perl. The symbol table is filled with names |
| 1403 | looking like line\-noise. |
| 1404 | .PP |
| 1405 | For the purpose of inheritance every overloaded package behaves as if |
| 1406 | \&\f(CW\*(C`fallback\*(C'\fR is present (possibly undefined). This may create |
| 1407 | interesting effects if some package is not overloaded, but inherits |
| 1408 | from two overloaded packages. |
| 1409 | .PP |
| 1410 | Relation between overloading and \fItie()\fRing is broken. Overloading is |
| 1411 | triggered or not basing on the \fIprevious\fR class of \fItie()\fRd value. |
| 1412 | .PP |
| 1413 | This happens because the presence of overloading is checked too early, |
| 1414 | before any \fItie()\fRd access is attempted. If the \s-1\fIFETCH\s0()\fRed class of the |
| 1415 | \&\fItie()\fRd value does not change, a simple workaround is to access the value |
| 1416 | immediately after \fItie()\fRing, so that after this call the \fIprevious\fR class |
| 1417 | coincides with the current one. |
| 1418 | .PP |
| 1419 | \&\fBNeeded:\fR a way to fix this without a speed penalty. |
| 1420 | .PP |
| 1421 | Barewords are not covered by overloaded string constants. |
| 1422 | .PP |
| 1423 | This document is confusing. There are grammos and misleading language |
| 1424 | used in places. It would seem a total rewrite is needed. |