.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.32 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "overload 3" .TH overload 3 "2001-09-21" "perl v5.8.8" "Perl Programmers Reference Guide" .SH "NAME" overload \- Package for overloading Perl operations .SH "SYNOPSIS" .IX Header "SYNOPSIS" .Vb 1 \& package SomeThing; .Ve .PP .Vb 5 \& use overload \& '+' => \e&myadd, \& '-' => \e&mysub; \& # etc \& ... .Ve .PP .Vb 7 \& package main; \& $a = new SomeThing 57; \& $b=5+$a; \& ... \& if (overload::Overloaded $b) {...} \& ... \& $strval = overload::StrVal $b; .Ve .SH "DESCRIPTION" .IX Header "DESCRIPTION" .Sh "Declaration of overloaded functions" .IX Subsection "Declaration of overloaded functions" The compilation directive .PP .Vb 4 \& package Number; \& use overload \& "+" => \e&add, \& "*=" => "muas"; .Ve .PP declares function \fINumber::add()\fR for addition, and method \fImuas()\fR in the \*(L"class\*(R" \f(CW\*(C`Number\*(C'\fR (or one of its base classes) for the assignment form \f(CW\*(C`*=\*(C'\fR of multiplication. .PP Arguments of this directive come in (key, value) pairs. Legal values are values legal inside a \f(CW\*(C`&{ ... }\*(C'\fR call, so the name of a subroutine, a reference to a subroutine, or an anonymous subroutine will all work. Note that values specified as strings are interpreted as methods, not subroutines. Legal keys are listed below. .PP 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 is a reference to an object blessed into the package \f(CW\*(C`Number\*(C'\fR, or if \f(CW$a\fR is not an object from a package with defined mathemagic addition, but \f(CW$b\fR is a reference to a \f(CW\*(C`Number\*(C'\fR. It can also be called in other situations, like \&\f(CW\*(C`$a+=7\*(C'\fR, or \f(CW\*(C`$a++\*(C'\fR. See \*(L"\s-1MAGIC\s0 \s-1AUTOGENERATION\s0\*(R". (Mathemagical methods refer to methods triggered by an overloaded mathematical operator.) .PP Since overloading respects inheritance via the \f(CW@ISA\fR hierarchy, the above declaration would also trigger overloading of \f(CW\*(C`+\*(C'\fR and \f(CW\*(C`*=\*(C'\fR in all the packages which inherit from \f(CW\*(C`Number\*(C'\fR. .Sh "Calling Conventions for Binary Operations" .IX Subsection "Calling Conventions for Binary Operations" The functions specified in the \f(CW\*(C`use overload ...\*(C'\fR directive are called with three (in one particular case with four, see \*(L"Last Resort\*(R") arguments. If the corresponding operation is binary, then the first two arguments are the two arguments of the operation. However, due to general object calling conventions, the first argument should always be an object in the package, so in the situation of \f(CW\*(C`7+$a\*(C'\fR, the order of the arguments is interchanged. It probably does not matter when implementing the addition method, but whether the arguments are reversed is vital to the subtraction method. The method can query this information by examining the third argument, which can take three different values: .IP "\s-1FALSE\s0" 7 .IX Item "FALSE" the order of arguments is as in the current operation. .IP "\s-1TRUE\s0" 7 .IX Item "TRUE" the arguments are reversed. .ie n .IP """undef""" 7 .el .IP "\f(CWundef\fR" 7 .IX Item "undef" the current operation is an assignment variant (as in \&\f(CW\*(C`$a+=7\*(C'\fR), but the usual function is called instead. This additional information can be used to generate some optimizations. Compare \&\*(L"Calling Conventions for Mutators\*(R". .Sh "Calling Conventions for Unary Operations" .IX Subsection "Calling Conventions for Unary Operations" Unary operation are considered binary operations with the second argument being \f(CW\*(C`undef\*(C'\fR. Thus the functions that overloads \f(CW\*(C`{"++"}\*(C'\fR is called with arguments \f(CW\*(C`($a,undef,'')\*(C'\fR when \f(CW$a\fR++ is executed. .Sh "Calling Conventions for Mutators" .IX Subsection "Calling Conventions for Mutators" Two types of mutators have different calling conventions: .ie n .IP """++""\fR and \f(CW""\-\-""" 4 .el .IP "\f(CW++\fR and \f(CW\-\-\fR" 4 .IX Item "++ and --" The routines which implement these operators are expected to actually \&\fImutate\fR their arguments. So, assuming that \f(CW$obj\fR is a reference to a number, .Sp .Vb 1 \& sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \e$n} .Ve .Sp is an appropriate implementation of overloaded \f(CW\*(C`++\*(C'\fR. Note that .Sp .Vb 1 \& sub incr { ++$ {$_[0]} ; shift } .Ve .Sp is \s-1OK\s0 if used with preincrement and with postincrement. (In the case of postincrement a copying will be performed, see \*(L"Copy Constructor\*(R".) .ie n .IP """x="" and other assignment versions" 4 .el .IP "\f(CWx=\fR and other assignment versions" 4 .IX Item "x= and other assignment versions" There is nothing special about these methods. They may change the value of their arguments, and may leave it as is. The result is going to be assigned to the value in the left-hand-side if different from this value. .Sp This allows for the same method to be used as overloaded \f(CW\*(C`+=\*(C'\fR and \&\f(CW\*(C`+\*(C'\fR. Note that this is \fIallowed\fR, but not recommended, since by the semantic of \*(L"Fallback\*(R" Perl will call the method for \f(CW\*(C`+\*(C'\fR anyway, if \f(CW\*(C`+=\*(C'\fR is not overloaded. .PP \&\fBWarning.\fR Due to the presence of assignment versions of operations, routines which may be called in assignment context may create self-referential structures. Currently Perl will not free self-referential structures until cycles are \f(CW\*(C`explicitly\*(C'\fR broken. You may get problems when traversing your structures too. .PP Say, .PP .Vb 1 \& use overload '+' => sub { bless [ \e$_[0], \e$_[1] ] }; .Ve .PP is asking for trouble, since for code \f(CW\*(C`$obj += $foo\*(C'\fR the subroutine is called as \f(CW\*(C`$obj = add($obj, $foo, undef)\*(C'\fR, or \f(CW\*(C`$obj = [\e$obj, \&\e$foo]\*(C'\fR. If using such a subroutine is an important optimization, one can overload \f(CW\*(C`+=\*(C'\fR explicitly by a non\-\*(L"optimized\*(R" version, or switch to non-optimized version if \f(CW\*(C`not defined $_[2]\*(C'\fR (see \&\*(L"Calling Conventions for Binary Operations\*(R"). .PP Even if no \fIexplicit\fR assignment-variants of operators are present in the script, they may be generated by the optimizer. Say, \f(CW",$obj,"\fR or \&\f(CW',' . $obj . ','\fR may be both optimized to .PP .Vb 1 \& my $tmp = ',' . $obj; $tmp .= ','; .Ve .Sh "Overloadable Operations" .IX Subsection "Overloadable Operations" The following symbols can be specified in \f(CW\*(C`use overload\*(C'\fR directive: .IP "* \fIArithmetic operations\fR" 5 .IX Item "Arithmetic operations" .Vb 2 \& "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=", \& "**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=", .Ve .Sp For these operations a substituted non-assignment variant can be called if the assignment variant is not available. Methods for operations \f(CW\*(C`+\*(C'\fR, \&\f(CW\*(C`\-\*(C'\fR, \f(CW\*(C`+=\*(C'\fR, and \f(CW\*(C`\-=\*(C'\fR can be called to automatically generate increment and decrement methods. The operation \f(CW\*(C`\-\*(C'\fR can be used to autogenerate missing methods for unary minus or \f(CW\*(C`abs\*(C'\fR. .Sp See \*(L"\s-1MAGIC\s0 \s-1AUTOGENERATION\s0\*(R", \*(L"Calling Conventions for Mutators\*(R" and \&\*(L"Calling Conventions for Binary Operations\*(R") for details of these substitutions. .IP "* \fIComparison operations\fR" 5 .IX Item "Comparison operations" .Vb 2 \& "<", "<=", ">", ">=", "==", "!=", "<=>", \& "lt", "le", "gt", "ge", "eq", "ne", "cmp", .Ve .Sp If the corresponding \*(L"spaceship\*(R" variant is available, it can be used to substitute for the missing operation. During \f(CW\*(C`sort\*(C'\fRing arrays, \f(CW\*(C`cmp\*(C'\fR is used to compare values subject to \f(CW\*(C`use overload\*(C'\fR. .IP "* \fIBit operations\fR" 5 .IX Item "Bit operations" .Vb 1 \& "&", "^", "|", "neg", "!", "~", .Ve .Sp \&\f(CW\*(C`neg\*(C'\fR stands for unary minus. If the method for \f(CW\*(C`neg\*(C'\fR is not specified, it can be autogenerated using the method for subtraction. If the method for \f(CW\*(C`!\*(C'\fR is not specified, it can be autogenerated using the methods for \f(CW\*(C`bool\*(C'\fR, or \f(CW""\fR, or \f(CW\*(C`0+\*(C'\fR. .IP "* \fIIncrement and decrement\fR" 5 .IX Item "Increment and decrement" .Vb 1 \& "++", "--", .Ve .Sp If undefined, addition and subtraction methods can be used instead. These operations are called both in prefix and postfix form. .IP "* \fITranscendental functions\fR" 5 .IX Item "Transcendental functions" .Vb 1 \& "atan2", "cos", "sin", "exp", "abs", "log", "sqrt", "int" .Ve .Sp If \f(CW\*(C`abs\*(C'\fR is unavailable, it can be autogenerated using methods for "<\*(L" or \*(R"<=>" combined with either unary minus or subtraction. .Sp Note that traditionally the Perl function int rounds to 0, thus for floating-point-like types one should follow the same semantic. If \&\f(CW\*(C`int\*(C'\fR is unavailable, it can be autogenerated using the overloading of \&\f(CW\*(C`0+\*(C'\fR. .IP "* \fIBoolean, string and numeric conversion\fR" 5 .IX Item "Boolean, string and numeric conversion" .Vb 1 \& 'bool', '""', '0+', .Ve .Sp If one or two of these operations are not overloaded, the remaining ones can be used instead. \f(CW\*(C`bool\*(C'\fR is used in the flow control operators (like \f(CW\*(C`while\*(C'\fR) and for the ternary \f(CW\*(C`?:\*(C'\fR operation. These functions can return any arbitrary Perl value. If the corresponding operation for this value is overloaded too, that operation will be called again with this value. .Sp As a special case if the overload returns the object itself then it will be used directly. An overloaded conversion returning the object is probably a bug, because you're likely to get something that looks like \&\f(CW\*(C`YourPackage=HASH(0x8172b34)\*(C'\fR. .IP "* \fIIteration\fR" 5 .IX Item "Iteration" .Vb 1 \& "<>" .Ve .Sp If not overloaded, the argument will be converted to a filehandle or glob (which may require a stringification). The same overloading happens both for the \fIread-filehandle\fR syntax \f(CW\*(C`<$var>\*(C'\fR and \&\fIglobbing\fR syntax \f(CW\*(C`<${var}>\*(C'\fR. .Sp \&\fB\s-1BUGS\s0\fR Even in list context, the iterator is currently called only once and with scalar context. .IP "* \fIDereferencing\fR" 5 .IX Item "Dereferencing" .Vb 1 \& '${}', '@{}', '%{}', '&{}', '*{}'. .Ve .Sp If not overloaded, the argument will be dereferenced \fIas is\fR, thus should be of correct type. These functions should return a reference of correct type, or another object with overloaded dereferencing. .Sp As a special case if the overload returns the object itself then it will be used directly (provided it is the correct type). .Sp The dereference operators must be specified explicitly they will not be passed to \&\*(L"nomethod\*(R". .IP "* \fISpecial\fR" 5 .IX Item "Special" .Vb 1 \& "nomethod", "fallback", "=", .Ve .Sp see "\s-1SPECIAL\s0 \s-1SYMBOLS\s0 \s-1FOR\s0 \f(CW\*(C`use overload\*(C'\fR". .PP See \*(L"Fallback\*(R" for an explanation of when a missing method can be autogenerated. .PP A computer-readable form of the above table is available in the hash \&\f(CW%overload::ops\fR, with values being space-separated lists of names: .PP .Vb 13 \& with_assign => '+ - * / % ** << >> x .', \& assign => '+= -= *= /= %= **= <<= >>= x= .=', \& num_comparison => '< <= > >= == !=', \& '3way_comparison'=> '<=> cmp', \& str_comparison => 'lt le gt ge eq ne', \& binary => '& | ^', \& unary => 'neg ! ~', \& mutators => '++ --', \& func => 'atan2 cos sin exp abs log sqrt', \& conversion => 'bool "" 0+', \& iterators => '<>', \& dereferencing => '${} @{} %{} &{} *{}', \& special => 'nomethod fallback =' .Ve .Sh "Inheritance and overloading" .IX Subsection "Inheritance and overloading" Inheritance interacts with overloading in two ways. .ie n .IP "Strings as values of ""use overload"" directive" 4 .el .IP "Strings as values of \f(CWuse overload\fR directive" 4 .IX Item "Strings as values of use overload directive" If \f(CW\*(C`value\*(C'\fR in .Sp .Vb 1 \& use overload key => value; .Ve .Sp is a string, it is interpreted as a method name. .IP "Overloading of an operation is inherited by derived classes" 4 .IX Item "Overloading of an operation is inherited by derived classes" Any class derived from an overloaded class is also overloaded. The set of overloaded methods is the union of overloaded methods of all the ancestors. If some method is overloaded in several ancestor, then which description will be used is decided by the usual inheritance rules: .Sp 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 \&\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, then the subroutine \f(CW\*(C`D::plus_sub\*(C'\fR will be called to implement operation \f(CW\*(C`+\*(C'\fR for an object in package \f(CW\*(C`A\*(C'\fR. .PP Note that since the value of the \f(CW\*(C`fallback\*(C'\fR key is not a subroutine, its inheritance is not governed by the above rules. In the current implementation, the value of \f(CW\*(C`fallback\*(C'\fR in the first overloaded ancestor is used, but this is accidental and subject to change. .ie n .SH "SPECIAL SYMBOLS FOR ""use overload""" .el .SH "SPECIAL SYMBOLS FOR \f(CWuse overload\fP" .IX Header "SPECIAL SYMBOLS FOR use overload" Three keys are recognized by Perl that are not covered by the above description. .Sh "Last Resort" .IX Subsection "Last Resort" \&\f(CW"nomethod"\fR should be followed by a reference to a function of four parameters. If defined, it is called when the overloading mechanism cannot find a method for some operation. The first three arguments of this function coincide with the arguments for the corresponding method if it were found, the fourth argument is the symbol corresponding to the missing method. If several methods are tried, the last one is used. Say, \f(CW\*(C`1\-$a\*(C'\fR can be equivalent to .PP .Vb 1 \& &nomethodMethod($a,1,1,"-") .Ve .PP if the pair \f(CW"nomethod" => "nomethodMethod"\fR was specified in the \&\f(CW\*(C`use overload\*(C'\fR directive. .PP The \f(CW"nomethod"\fR mechanism is \fInot\fR used for the dereference operators ( ${} @{} %{} &{} *{} ). .PP If some operation cannot be resolved, and there is no function assigned to \f(CW"nomethod"\fR, then an exception will be raised via \fIdie()\fR\-\- unless \f(CW"fallback"\fR was specified as a key in \f(CW\*(C`use overload\*(C'\fR directive. .Sh "Fallback" .IX Subsection "Fallback" The key \f(CW"fallback"\fR governs what to do if a method for a particular operation is not found. Three different cases are possible depending on the value of \f(CW"fallback"\fR: .ie n .IP "* ""undef""" 16 .el .IP "* \f(CWundef\fR" 16 .IX Item "undef" Perl tries to use a substituted method (see \*(L"\s-1MAGIC\s0 \s-1AUTOGENERATION\s0\*(R"). If this fails, it then tries to calls \f(CW"nomethod"\fR value; if missing, an exception will be raised. .IP "* \s-1TRUE\s0" 16 .IX Item "TRUE" The same as for the \f(CW\*(C`undef\*(C'\fR value, but no exception is raised. Instead, it silently reverts to what it would have done were there no \f(CW\*(C`use overload\*(C'\fR present. .IP "* defined, but \s-1FALSE\s0" 16 .IX Item "defined, but FALSE" No autogeneration is tried. Perl tries to call \&\f(CW"nomethod"\fR value, and if this is missing, raises an exception. .PP \&\fBNote.\fR \f(CW"fallback"\fR inheritance via \f(CW@ISA\fR is not carved in stone yet, see \*(L"Inheritance and overloading\*(R". .Sh "Copy Constructor" .IX Subsection "Copy Constructor" The value for \f(CW"="\fR is a reference to a function with three arguments, i.e., it looks like the other values in \f(CW\*(C`use overload\*(C'\fR. However, it does not overload the Perl assignment operator. This would go against Camel hair. .PP This operation is called in the situations when a mutator is applied to a reference that shares its object with some other reference, such as .PP .Vb 2 \& $a=$b; \& ++$a; .Ve .PP To make this change \f(CW$a\fR and not change \f(CW$b\fR, a copy of \f(CW$$a\fR is made, and \f(CW$a\fR is assigned a reference to this new object. This operation is done during execution of the \f(CW\*(C`++$a\*(C'\fR, and not during the assignment, (so before the increment \f(CW$$a\fR coincides with \f(CW$$b\fR). This is only done if \f(CW\*(C`++\*(C'\fR is expressed via a method for \f(CW'++'\fR or \f(CW'+='\fR (or \&\f(CW\*(C`nomethod\*(C'\fR). Note that if this operation is expressed via \f(CW'+'\fR a nonmutator, i.e., as in .PP .Vb 2 \& $a=$b; \& $a=$a+1; .Ve .PP then \f(CW$a\fR does not reference a new copy of \f(CW$$a\fR, since $$a does not appear as lvalue when the above code is executed. .PP If the copy constructor is required during the execution of some mutator, but a method for \f(CW'='\fR was not specified, it can be autogenerated as a string copy if the object is a plain scalar. .IP "\fBExample\fR" 5 .IX Item "Example" The actually executed code for .Sp .Vb 3 \& $a=$b; \& Something else which does not modify $a or $b.... \& ++$a; .Ve .Sp may be .Sp .Vb 4 \& $a=$b; \& Something else which does not modify $a or $b.... \& $a = $a->clone(undef,""); \& $a->incr(undef,""); .Ve .Sp if \f(CW$b\fR was mathemagical, and \f(CW'++'\fR was overloaded with \f(CW\*(C`\e&incr\*(C'\fR, \&\f(CW'='\fR was overloaded with \f(CW\*(C`\e&clone\*(C'\fR. .PP Same behaviour is triggered by \f(CW\*(C`$b = $a++\*(C'\fR, which is consider a synonym for \&\f(CW\*(C`$b = $a; ++$a\*(C'\fR. .SH "MAGIC AUTOGENERATION" .IX Header "MAGIC AUTOGENERATION" If a method for an operation is not found, and the value for \f(CW"fallback"\fR is \&\s-1TRUE\s0 or undefined, Perl tries to autogenerate a substitute method for the missing operation based on the defined operations. Autogenerated method substitutions are possible for the following operations: .IP "\fIAssignment forms of arithmetic operations\fR" 16 .IX Item "Assignment forms of arithmetic operations" \&\f(CW\*(C`$a+=$b\*(C'\fR can use the method for \f(CW"+"\fR if the method for \f(CW"+="\fR is not defined. .IP "\fIConversion operations\fR" 16 .IX Item "Conversion operations" String, numeric, and boolean conversion are calculated in terms of one another if not all of them are defined. .IP "\fIIncrement and decrement\fR" 16 .IX Item "Increment and decrement" 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, 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. .ie n .IP """abs($a)""" 16 .el .IP "\f(CWabs($a)\fR" 16 .IX Item "abs($a)" 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). .IP "\fIUnary minus\fR" 16 .IX Item "Unary minus" can be expressed in terms of subtraction. .IP "\fINegation\fR" 16 .IX Item "Negation" \&\f(CW\*(C`!\*(C'\fR and \f(CW\*(C`not\*(C'\fR can be expressed in terms of boolean conversion, or string or numerical conversion. .IP "\fIConcatenation\fR" 16 .IX Item "Concatenation" can be expressed in terms of string conversion. .IP "\fIComparison operations\fR" 16 .IX Item "Comparison operations" can be expressed in terms of its \*(L"spaceship\*(R" counterpart: either \&\f(CW\*(C`<=>\*(C'\fR or \f(CW\*(C`cmp\*(C'\fR: .Sp .Vb 2 \& <, >, <=, >=, ==, != in terms of <=> \& lt, gt, le, ge, eq, ne in terms of cmp .Ve .IP "\fIIterator\fR" 16 .IX Item "Iterator" .Vb 1 \& <> in terms of builtin operations .Ve .IP "\fIDereferencing\fR" 16 .IX Item "Dereferencing" .Vb 1 \& ${} @{} %{} &{} *{} in terms of builtin operations .Ve .IP "\fICopy operator\fR" 16 .IX Item "Copy operator" can be expressed in terms of an assignment to the dereferenced value, if this value is a scalar and not a reference. .SH "Losing overloading" .IX Header "Losing overloading" The restriction for the comparison operation is that even if, for example, `\f(CW\*(C`cmp\*(C'\fR' should return a blessed reference, the autogenerated `\f(CW\*(C`lt\*(C'\fR' function will produce only a standard logical value based on the numerical value of the result of `\f(CW\*(C`cmp\*(C'\fR'. In particular, a working numeric conversion is needed in this case (possibly expressed in terms of other conversions). .PP Similarly, \f(CW\*(C`.=\*(C'\fR and \f(CW\*(C`x=\*(C'\fR operators lose their mathemagical properties if the string conversion substitution is applied. .PP When you \fIchop()\fR a mathemagical object it is promoted to a string and its mathemagical properties are lost. The same can happen with other operations as well. .SH "Run-time Overloading" .IX Header "Run-time Overloading" Since all \f(CW\*(C`use\*(C'\fR directives are executed at compile\-time, the only way to change overloading during run-time is to .PP .Vb 1 \& eval 'use overload "+" => \e&addmethod'; .Ve .PP You can also use .PP .Vb 1 \& eval 'no overload "+", "--", "<="'; .Ve .PP though the use of these constructs during run-time is questionable. .SH "Public functions" .IX Header "Public functions" Package \f(CW\*(C`overload.pm\*(C'\fR provides the following public functions: .IP "overload::StrVal(arg)" 5 .IX Item "overload::StrVal(arg)" Gives string value of \f(CW\*(C`arg\*(C'\fR as in absence of stringify overloading. If you are using this to get the address of a reference (useful for checking if two references point to the same thing) then you may be better off using \&\f(CW\*(C`Scalar::Util::refaddr()\*(C'\fR, which is faster. .IP "overload::Overloaded(arg)" 5 .IX Item "overload::Overloaded(arg)" Returns true if \f(CW\*(C`arg\*(C'\fR is subject to overloading of some operations. .IP "overload::Method(obj,op)" 5 .IX Item "overload::Method(obj,op)" Returns \f(CW\*(C`undef\*(C'\fR or a reference to the method that implements \f(CW\*(C`op\*(C'\fR. .SH "Overloading constants" .IX Header "Overloading constants" For some applications, the Perl parser mangles constants too much. It is possible to hook into this process via \f(CW\*(C`overload::constant()\*(C'\fR and \f(CW\*(C`overload::remove_constant()\*(C'\fR functions. .PP These functions take a hash as an argument. The recognized keys of this hash are: .IP "integer" 8 .IX Item "integer" to overload integer constants, .IP "float" 8 .IX Item "float" to overload floating point constants, .IP "binary" 8 .IX Item "binary" to overload octal and hexadecimal constants, .IP "q" 8 .IX Item "q" 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 strings and here\-documents, .IP "qr" 8 .IX Item "qr" to overload constant pieces of regular expressions. .PP The corresponding values are references to functions which take three arguments: the first one is the \fIinitial\fR string form of the constant, the second one is how Perl interprets this constant, the third one is how the constant is used. Note that the initial string form does not contain string delimiters, and has backslashes in backslash-delimiter combinations stripped (thus the value of delimiter is not relevant for processing of this string). The return value of this function is how this constant is going to be interpreted by Perl. The third argument is undefined 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 context (comes from strings, regular expressions, and single-quote \s-1HERE\s0 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, 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. .PP Since an expression \f(CW"ab$cd,,"\fR is just a shortcut for \f(CW'ab' . $cd . ',,'\fR, it is expected that overloaded constant strings are equipped with reasonable overloaded catenation operator, otherwise absurd results will result. Similarly, negative numbers are considered as negations of positive constants. .PP Note that it is probably meaningless to call the functions \fIoverload::constant()\fR and \fIoverload::remove_constant()\fR from anywhere but \fIimport()\fR and \fIunimport()\fR methods. From these methods they may be called as .PP .Vb 6 \& sub import { \& shift; \& return unless @_; \& die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant'; \& overload::constant integer => sub {Math::BigInt->new(shift)}; \& } .Ve .PP \&\fB\s-1BUGS\s0\fR Currently overloaded-ness of constants does not propagate into \f(CW\*(C`eval '...'\*(C'\fR. .SH "IMPLEMENTATION" .IX Header "IMPLEMENTATION" What follows is subject to change \s-1RSN\s0. .PP The table of methods for all operations is cached in magic for the symbol table hash for the package. The cache is invalidated during processing of \f(CW\*(C`use overload\*(C'\fR, \f(CW\*(C`no overload\*(C'\fR, new function definitions, and changes in \f(CW@ISA\fR. However, this invalidation remains unprocessed until the next \f(CW\*(C`bless\*(C'\fRing into the package. Hence if you want to change overloading structure dynamically, you'll need an additional (fake) \f(CW\*(C`bless\*(C'\fRing to update the table. .PP (Every SVish thing has a magic queue, and magic is an entry in that queue. This is how a single variable may participate in multiple forms of magic simultaneously. For instance, environment variables regularly have two forms at once: their \f(CW%ENV\fR magic and their taint magic. However, the magic which implements overloading is applied to the stashes, which are rarely used directly, thus should not slow down Perl.) .PP If an object belongs to a package using overload, it carries a special flag. Thus the only speed penalty during arithmetic operations without overloading is the checking of this flag. .PP In fact, if \f(CW\*(C`use overload\*(C'\fR is not present, there is almost no overhead for overloadable operations, so most programs should not suffer measurable performance penalties. A considerable effort was made to minimize the overhead when overload is used in some package, but the arguments in question do not belong to packages using overload. When in doubt, test your speed with \f(CW\*(C`use overload\*(C'\fR and without it. So far there have been no reports of substantial speed degradation if Perl is compiled with optimization turned on. .PP There is no size penalty for data if overload is not used. The only size penalty if overload is used in some package is that \fIall\fR the packages acquire a magic during the next \f(CW\*(C`bless\*(C'\fRing into the package. This magic is three-words-long for packages without overloading, and carries the cache table if the package is overloaded. .PP Copying (\f(CW\*(C`$a=$b\*(C'\fR) is shallow; however, a one-level-deep copying is carried out before any operation that can imply an assignment to the object \f(CW$a\fR (or \f(CW$b\fR) refers to, like \f(CW\*(C`$a++\*(C'\fR. You can override this behavior by defining your own copy constructor (see \*(L"Copy Constructor\*(R"). .PP It is expected that arguments to methods that are not explicitly supposed to be changed are constant (but this is not enforced). .SH "Metaphor clash" .IX Header "Metaphor clash" One may wonder why the semantic of overloaded \f(CW\*(C`=\*(C'\fR is so counter intuitive. If it \fIlooks\fR counter intuitive to you, you are subject to a metaphor clash. .PP Here is a Perl object metaphor: .PP \&\fI object is a reference to blessed data\fR .PP and an arithmetic metaphor: .PP \&\fI object is a thing by itself\fR. .PP The \fImain\fR problem of overloading \f(CW\*(C`=\*(C'\fR is the fact that these metaphors imply different actions on the assignment \f(CW\*(C`$a = $b\*(C'\fR if \f(CW$a\fR and \f(CW$b\fR are objects. Perl-think implies that \f(CW$a\fR becomes a reference to whatever \&\f(CW$b\fR was referencing. Arithmetic-think implies that the value of \*(L"object\*(R" \&\f(CW$a\fR is changed to become the value of the object \f(CW$b\fR, preserving the fact that \f(CW$a\fR and \f(CW$b\fR are separate entities. .PP The difference is not relevant in the absence of mutators. After a Perl-way assignment an operation which mutates the data referenced by \f(CW$a\fR would change the data referenced by \f(CW$b\fR too. Effectively, after \&\f(CW\*(C`$a = $b\*(C'\fR values of \f(CW$a\fR and \f(CW$b\fR become \fIindistinguishable\fR. .PP On the other hand, anyone who has used algebraic notation knows the expressive power of the arithmetic metaphor. Overloading works hard to enable this metaphor while preserving the Perlian way as far as possible. Since it is not possible to freely mix two contradicting metaphors, overloading allows the arithmetic way to write things \fIas far as all the mutators are called via overloaded access only\fR. The way it is done is described in \*(L"Copy Constructor\*(R". .PP If some mutator methods are directly applied to the overloaded values, one may need to \fIexplicitly unlink\fR other values which references the same value: .PP .Vb 6 \& $a = new Data 23; \& ... \& $b = $a; # $b is "linked" to $a \& ... \& $a = $a->clone; # Unlink $b from $a \& $a->increment_by(4); .Ve .PP Note that overloaded access makes this transparent: .PP .Vb 3 \& $a = new Data 23; \& $b = $a; # $b is "linked" to $a \& $a += 4; # would unlink $b automagically .Ve .PP However, it would not make .PP .Vb 2 \& $a = new Data 23; \& $a = 4; # Now $a is a plain 4, not 'Data' .Ve .PP preserve \*(L"objectness\*(R" of \f(CW$a\fR. But Perl \fIhas\fR a way to make assignments to an object do whatever you want. It is just not the overload, but \&\fItie()\fRing interface (see \*(L"tie\*(R" in perlfunc). Adding a \s-1\fIFETCH\s0()\fR method which returns the object itself, and \s-1\fISTORE\s0()\fR method which changes the value of the object, one can reproduce the arithmetic metaphor in its completeness, at least for variables which were \fItie()\fRd from the start. .PP (Note that a workaround for a bug may be needed, see \*(L"\s-1BUGS\s0\*(R".) .SH "Cookbook" .IX Header "Cookbook" Please add examples to what follows! .Sh "Two-face scalars" .IX Subsection "Two-face scalars" Put this in \fItwo_face.pm\fR in your Perl library directory: .PP .Vb 6 \& package two_face; # Scalars with separate string and \& # numeric values. \& sub new { my $p = shift; bless [@_], $p } \& use overload '""' => \e&str, '0+' => \e&num, fallback => 1; \& sub num {shift->[1]} \& sub str {shift->[0]} .Ve .PP Use it as follows: .PP .Vb 4 \& require two_face; \& my $seven = new two_face ("vii", 7); \& printf "seven=$seven, seven=%d, eight=%d\en", $seven, $seven+1; \& print "seven contains `i'\en" if $seven =~ /i/; .Ve .PP (The second line creates a scalar which has both a string value, and a numeric value.) This prints: .PP .Vb 2 \& seven=vii, seven=7, eight=8 \& seven contains `i' .Ve .Sh "Two-face references" .IX Subsection "Two-face references" Suppose you want to create an object which is accessible as both an array reference and a hash reference, similar to the pseudo-hash builtin Perl type. Let's make it better than a pseudo-hash by allowing index 0 to be treated as a normal element. .PP .Vb 12 \& package two_refs; \& use overload '%{}' => \e&gethash, '@{}' => sub { $ {shift()} }; \& sub new { \& my $p = shift; \& bless \e [@_], $p; \& } \& sub gethash { \& my %h; \& my $self = shift; \& tie %h, ref $self, $self; \& \e%h; \& } .Ve .PP .Vb 16 \& sub TIEHASH { my $p = shift; bless \e shift, $p } \& my %fields; \& my $i = 0; \& $fields{$_} = $i++ foreach qw{zero one two three}; \& sub STORE { \& my $self = ${shift()}; \& my $key = $fields{shift()}; \& defined $key or die "Out of band access"; \& $$self->[$key] = shift; \& } \& sub FETCH { \& my $self = ${shift()}; \& my $key = $fields{shift()}; \& defined $key or die "Out of band access"; \& $$self->[$key]; \& } .Ve .PP Now one can access an object using both the array and hash syntax: .PP .Vb 3 \& my $bar = new two_refs 3,4,5,6; \& $bar->[2] = 11; \& $bar->{two} == 11 or die 'bad hash fetch'; .Ve .PP Note several important features of this example. First of all, the \&\fIactual\fR type of \f(CW$bar\fR is a scalar reference, and we do not overload the scalar dereference. Thus we can get the \fIactual\fR non-overloaded contents of \f(CW$bar\fR by just using \f(CW$$bar\fR (what we do in functions which overload dereference). Similarly, the object returned by the \&\s-1\fITIEHASH\s0()\fR method is a scalar reference. .PP Second, we create a new tied hash each time the hash syntax is used. This allows us not to worry about a possibility of a reference loop, which would lead to a memory leak. .PP Both these problems can be cured. Say, if we want to overload hash dereference on a reference to an object which is \fIimplemented\fR as a hash itself, the only problem one has to circumvent is how to access this \fIactual\fR hash (as opposed to the \fIvirtual\fR hash exhibited by the overloaded dereference operator). Here is one possible fetching routine: .PP .Vb 8 \& sub access_hash { \& my ($self, $key) = (shift, shift); \& my $class = ref $self; \& bless $self, 'overload::dummy'; # Disable overloading of %{} \& my $out = $self->{$key}; \& bless $self, $class; # Restore overloading \& $out; \& } .Ve .PP To remove creation of the tied hash on each access, one may an extra level of indirection which allows a non-circular structure of references: .PP .Vb 16 \& package two_refs1; \& use overload '%{}' => sub { ${shift()}->[1] }, \& '@{}' => sub { ${shift()}->[0] }; \& sub new { \& my $p = shift; \& my $a = [@_]; \& my %h; \& tie %h, $p, $a; \& bless \e [$a, \e%h], $p; \& } \& sub gethash { \& my %h; \& my $self = shift; \& tie %h, ref $self, $self; \& \e%h; \& } .Ve .PP .Vb 16 \& sub TIEHASH { my $p = shift; bless \e shift, $p } \& my %fields; \& my $i = 0; \& $fields{$_} = $i++ foreach qw{zero one two three}; \& sub STORE { \& my $a = ${shift()}; \& my $key = $fields{shift()}; \& defined $key or die "Out of band access"; \& $a->[$key] = shift; \& } \& sub FETCH { \& my $a = ${shift()}; \& my $key = $fields{shift()}; \& defined $key or die "Out of band access"; \& $a->[$key]; \& } .Ve .PP Now if \f(CW$baz\fR is overloaded like this, then \f(CW$baz\fR is a reference to a reference to the intermediate array, which keeps a reference to an actual array, and the access hash. The \fItie()\fRing object for the access hash is a reference to a reference to the actual array, so .IP "\(bu" 4 There are no loops of references. .IP "\(bu" 4 Both \*(L"objects\*(R" which are blessed into the class \f(CW\*(C`two_refs1\*(C'\fR are references to a reference to an array, thus references to a \fIscalar\fR. Thus the accessor expression \f(CW\*(C`$$foo\->[$ind]\*(C'\fR involves no overloaded operations. .Sh "Symbolic calculator" .IX Subsection "Symbolic calculator" Put this in \fIsymbolic.pm\fR in your Perl library directory: .PP .Vb 2 \& package symbolic; # Primitive symbolic calculator \& use overload nomethod => \e&wrap; .Ve .PP .Vb 6 \& sub new { shift; bless ['n', @_] } \& sub wrap { \& my ($obj, $other, $inv, $meth) = @_; \& ($obj, $other) = ($other, $obj) if $inv; \& bless [$meth, $obj, $other]; \& } .Ve .PP This module is very unusual as overloaded modules go: it does not 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 subroutine returns an object which encapsulates operations done over the objects: \f(CW\*(C`new symbolic 3\*(C'\fR contains \f(CW\*(C`['n', 3]\*(C'\fR, \f(CW\*(C`2 + new symbolic 3\*(C'\fR contains \f(CW\*(C`['+', 2, ['n', 3]]\*(C'\fR. .PP Here is an example of the script which \*(L"calculates\*(R" the side of circumscribed octagon using the above package: .PP .Vb 4 \& require symbolic; \& my $iter = 1; # 2**($iter+2) = 8 \& my $side = new symbolic 1; \& my $cnt = $iter; .Ve .PP .Vb 4 \& while ($cnt--) { \& $side = (sqrt(1 + $side**2) - 1)/$side; \& } \& print "OK\en"; .Ve .PP The value of \f(CW$side\fR is .PP .Vb 2 \& ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]], \& undef], 1], ['n', 1]] .Ve .PP Note that while we obtained this value using a nice little script, there is no simple way to \fIuse\fR this value. In fact this value may be inspected in debugger (see perldebug), but ony if \&\f(CW\*(C`bareStringify\*(C'\fR \fBO\fRption is set, and not via \f(CW\*(C`p\*(C'\fR command. .PP If one attempts to print this value, then the overloaded operator \&\f(CW""\fR will be called, which will call \f(CW\*(C`nomethod\*(C'\fR operator. The result of this operator will be stringified again, but this result is again of type \f(CW\*(C`symbolic\*(C'\fR, which will lead to an infinite loop. .PP Add a pretty-printer method to the module \fIsymbolic.pm\fR: .PP .Vb 8 \& sub pretty { \& my ($meth, $a, $b) = @{+shift}; \& $a = 'u' unless defined $a; \& $b = 'u' unless defined $b; \& $a = $a->pretty if ref $a; \& $b = $b->pretty if ref $b; \& "[$meth $a $b]"; \& } .Ve .PP Now one can finish the script by .PP .Vb 1 \& print "side = ", $side->pretty, "\en"; .Ve .PP The method \f(CW\*(C`pretty\*(C'\fR is doing object-to-string conversion, so it is natural to overload the operator \f(CW""\fR using this method. However, inside such a method it is not necessary to pretty-print the \&\fIcomponents\fR \f(CW$a\fR and \f(CW$b\fR of an object. In the above subroutine \&\f(CW"[$meth $a $b]"\fR is a catenation of some strings and components \f(CW$a\fR and \f(CW$b\fR. If these components use overloading, the catenation operator will look for an overloaded operator \f(CW\*(C`.\*(C'\fR; if not present, it will look for an overloaded operator \f(CW""\fR. Thus it is enough to use .PP .Vb 7 \& use overload nomethod => \e&wrap, '""' => \e&str; \& sub str { \& my ($meth, $a, $b) = @{+shift}; \& $a = 'u' unless defined $a; \& $b = 'u' unless defined $b; \& "[$meth $a $b]"; \& } .Ve .PP Now one can change the last line of the script to .PP .Vb 1 \& print "side = $side\en"; .Ve .PP which outputs .PP .Vb 1 \& side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]] .Ve .PP and one can inspect the value in debugger using all the possible methods. .PP Something is still amiss: consider the loop variable \f(CW$cnt\fR of the script. It was a number, not an object. We cannot make this value of type \f(CW\*(C`symbolic\*(C'\fR, since then the loop will not terminate. .PP Indeed, to terminate the cycle, the \f(CW$cnt\fR should become false. However, the operator \f(CW\*(C`bool\*(C'\fR for checking falsity is overloaded (this time via overloaded \f(CW""\fR), and returns a long string, thus any object of type \f(CW\*(C`symbolic\*(C'\fR is true. To overcome this, we need a way to compare an object to 0. In fact, it is easier to write a numeric conversion routine. .PP Here is the text of \fIsymbolic.pm\fR with such a routine added (and slightly modified \fIstr()\fR): .PP .Vb 3 \& package symbolic; # Primitive symbolic calculator \& use overload \& nomethod => \e&wrap, '""' => \e&str, '0+' => \e# .Ve .PP .Vb 31 \& sub new { shift; bless ['n', @_] } \& sub wrap { \& my ($obj, $other, $inv, $meth) = @_; \& ($obj, $other) = ($other, $obj) if $inv; \& bless [$meth, $obj, $other]; \& } \& sub str { \& my ($meth, $a, $b) = @{+shift}; \& $a = 'u' unless defined $a; \& if (defined $b) { \& "[$meth $a $b]"; \& } else { \& "[$meth $a]"; \& } \& } \& my %subr = ( n => sub {$_[0]}, \& sqrt => sub {sqrt $_[0]}, \& '-' => sub {shift() - shift()}, \& '+' => sub {shift() + shift()}, \& '/' => sub {shift() / shift()}, \& '*' => sub {shift() * shift()}, \& '**' => sub {shift() ** shift()}, \& ); \& sub num { \& my ($meth, $a, $b) = @{+shift}; \& my $subr = $subr{$meth} \& or die "Do not know how to ($meth) in symbolic"; \& $a = $a->num if ref $a eq __PACKAGE__; \& $b = $b->num if ref $b eq __PACKAGE__; \& $subr->($a,$b); \& } .Ve .PP All the work of numeric conversion is done in \f(CW%subr\fR and \fInum()\fR. Of course, \f(CW%subr\fR is not complete, it contains only operators used in the example below. Here is the extra-credit question: why do we need an explicit recursion in \fInum()\fR? (Answer is at the end of this section.) .PP Use this module like this: .PP .Vb 4 \& require symbolic; \& my $iter = new symbolic 2; # 16-gon \& my $side = new symbolic 1; \& my $cnt = $iter; .Ve .PP .Vb 6 \& while ($cnt) { \& $cnt = $cnt - 1; # Mutator `--' not implemented \& $side = (sqrt(1 + $side**2) - 1)/$side; \& } \& printf "%s=%f\en", $side, $side; \& printf "pi=%f\en", $side*(2**($iter+2)); .Ve .PP It prints (without so many line breaks) .PP .Vb 4 \& [/ [- [sqrt [+ 1 [** [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] \& [n 1]] 2]]] 1] \& [/ [- [sqrt [+ 1 [** [n 1] 2]]] 1] [n 1]]]=0.198912 \& pi=3.182598 .Ve .PP The above module is very primitive. It does not implement mutator methods (\f(CW\*(C`++\*(C'\fR, \f(CW\*(C`\-=\*(C'\fR and so on), does not do deep copying (not required without mutators!), and implements only those arithmetic operations which are used in the example. .PP To implement most arithmetic operations is easy; one should just use the tables of operations, and change the code which fills \f(CW%subr\fR to .PP .Vb 12 \& my %subr = ( 'n' => sub {$_[0]} ); \& foreach my $op (split " ", $overload::ops{with_assign}) { \& $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}"; \& } \& my @bins = qw(binary 3way_comparison num_comparison str_comparison); \& foreach my $op (split " ", "@overload::ops{ @bins }") { \& $subr{$op} = eval "sub {shift() $op shift()}"; \& } \& foreach my $op (split " ", "@overload::ops{qw(unary func)}") { \& print "defining `$op'\en"; \& $subr{$op} = eval "sub {$op shift()}"; \& } .Ve .PP Due to \*(L"Calling Conventions for Mutators\*(R", we do not need anything special to make \f(CW\*(C`+=\*(C'\fR and friends work, except filling \f(CW\*(C`+=\*(C'\fR entry of \&\f(CW%subr\fR, and defining a copy constructor (needed since Perl has no way to know that the implementation of \f(CW'+='\fR does not mutate the argument, compare \*(L"Copy Constructor\*(R"). .PP To implement a copy constructor, add \f(CW\*(C`'=' => \e&cpy\*(C'\fR to \f(CW\*(C`use overload\*(C'\fR line, and code (this code assumes that mutators change things one level deep only, so recursive copying is not needed): .PP .Vb 4 \& sub cpy { \& my $self = shift; \& bless [@$self], ref $self; \& } .Ve .PP To make \f(CW\*(C`++\*(C'\fR and \f(CW\*(C`\-\-\*(C'\fR work, we need to implement actual mutators, either directly, or in \f(CW\*(C`nomethod\*(C'\fR. We continue to do things inside \&\f(CW\*(C`nomethod\*(C'\fR, thus add .PP .Vb 4 \& if ($meth eq '++' or $meth eq '--') { \& @$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference \& return $obj; \& } .Ve .PP after the first line of \fIwrap()\fR. This is not a most effective implementation, one may consider .PP .Vb 1 \& sub inc { $_[0] = bless ['++', shift, 1]; } .Ve .PP instead. .PP As a final remark, note that one can fill \f(CW%subr\fR by .PP .Vb 13 \& my %subr = ( 'n' => sub {$_[0]} ); \& foreach my $op (split " ", $overload::ops{with_assign}) { \& $subr{$op} = $subr{"$op="} = eval "sub {shift() $op shift()}"; \& } \& my @bins = qw(binary 3way_comparison num_comparison str_comparison); \& foreach my $op (split " ", "@overload::ops{ @bins }") { \& $subr{$op} = eval "sub {shift() $op shift()}"; \& } \& foreach my $op (split " ", "@overload::ops{qw(unary func)}") { \& $subr{$op} = eval "sub {$op shift()}"; \& } \& $subr{'++'} = $subr{'+'}; \& $subr{'--'} = $subr{'-'}; .Ve .PP This finishes implementation of a primitive symbolic calculator in 50 lines of Perl code. Since the numeric values of subexpressions are not cached, the calculator is very slow. .PP Here is the answer for the exercise: In the case of \fIstr()\fR, we need no explicit recursion since the overloaded \f(CW\*(C`.\*(C'\fR\-operator will fall back to an existing overloaded operator \f(CW""\fR. Overloaded arithmetic operators \fIdo not\fR fall back to numeric conversion if \f(CW\*(C`fallback\*(C'\fR is not explicitly requested. Thus without an explicit recursion \fInum()\fR would convert \f(CW\*(C`['+', $a, $b]\*(C'\fR to \f(CW\*(C`$a + $b\*(C'\fR, which would just rebuild the argument of \fInum()\fR. .PP If you wonder why defaults for conversion are different for \fIstr()\fR and \&\fInum()\fR, note how easy it was to write the symbolic calculator. This simplicity is due to an appropriate choice of defaults. One extra note: due to the explicit recursion \fInum()\fR is more fragile than \fIsym()\fR: we need to explicitly check for the type of \f(CW$a\fR and \f(CW$b\fR. If components \&\f(CW$a\fR and \f(CW$b\fR happen to be of some related type, this may lead to problems. .Sh "\fIReally\fP symbolic calculator" .IX Subsection "Really symbolic calculator" One may wonder why we call the above calculator symbolic. The reason is that the actual calculation of the value of expression is postponed until the value is \fIused\fR. .PP To see it in action, add a method .PP .Vb 5 \& sub STORE { \& my $obj = shift; \& $#$obj = 1; \& @$obj->[0,1] = ('=', shift); \& } .Ve .PP to the package \f(CW\*(C`symbolic\*(C'\fR. After this change one can do .PP .Vb 3 \& my $a = new symbolic 3; \& my $b = new symbolic 4; \& my $c = sqrt($a**2 + $b**2); .Ve .PP and the numeric value of \f(CW$c\fR becomes 5. However, after calling .PP .Vb 1 \& $a->STORE(12); $b->STORE(5); .Ve .PP the numeric value of \f(CW$c\fR becomes 13. There is no doubt now that the module symbolic provides a \fIsymbolic\fR calculator indeed. .PP To hide the rough edges under the hood, provide a \fItie()\fRd interface to the package \f(CW\*(C`symbolic\*(C'\fR (compare with \*(L"Metaphor clash\*(R"). Add methods .PP .Vb 3 \& sub TIESCALAR { my $pack = shift; $pack->new(@_) } \& sub FETCH { shift } \& sub nop { } # Around a bug .Ve .PP (the bug is described in \*(L"\s-1BUGS\s0\*(R"). One can use this new interface as .PP .Vb 3 \& tie $a, 'symbolic', 3; \& tie $b, 'symbolic', 4; \& $a->nop; $b->nop; # Around a bug .Ve .PP .Vb 1 \& my $c = sqrt($a**2 + $b**2); .Ve .PP Now numeric value of \f(CW$c\fR is 5. After \f(CW\*(C`$a = 12; $b = 5\*(C'\fR the numeric value of \f(CW$c\fR becomes 13. To insulate the user of the module add a method .PP .Vb 1 \& sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; } .Ve .PP Now .PP .Vb 3 \& my ($a, $b); \& symbolic->vars($a, $b); \& my $c = sqrt($a**2 + $b**2); .Ve .PP .Vb 2 \& $a = 3; $b = 4; \& printf "c5 %s=%f\en", $c, $c; .Ve .PP .Vb 2 \& $a = 12; $b = 5; \& printf "c13 %s=%f\en", $c, $c; .Ve .PP shows that the numeric value of \f(CW$c\fR follows changes to the values of \f(CW$a\fR and \f(CW$b\fR. .SH "AUTHOR" .IX Header "AUTHOR" Ilya Zakharevich <\fIilya@math.mps.ohio\-state.edu\fR>. .SH "DIAGNOSTICS" .IX Header "DIAGNOSTICS" When Perl is run with the \fB\-Do\fR switch or its equivalent, overloading induces diagnostic messages. .PP Using the \f(CW\*(C`m\*(C'\fR command of Perl debugger (see perldebug) one can deduce which operations are overloaded (and which ancestor triggers this overloading). Say, if \f(CW\*(C`eq\*(C'\fR is overloaded, then the method \f(CW\*(C`(eq\*(C'\fR is shown by debugger. The method \f(CW\*(C`()\*(C'\fR corresponds to the \f(CW\*(C`fallback\*(C'\fR key (in fact a presence of this method shows that this package has overloading enabled, and it is what is used by the \f(CW\*(C`Overloaded\*(C'\fR function of module \f(CW\*(C`overload\*(C'\fR). .PP The module might issue the following warnings: .IP "Odd number of arguments for overload::constant" 4 .IX Item "Odd number of arguments for overload::constant" (W) The call to overload::constant contained an odd number of arguments. The arguments should come in pairs. .IP "`%s' is not an overloadable type" 4 .IX Item "`%s' is not an overloadable type" (W) You tried to overload a constant type the overload package is unaware of. .IP "`%s' is not a code reference" 4 .IX Item "`%s' is not a code reference" (W) The second (fourth, sixth, ...) argument of overload::constant needs to be a code reference. Either an anonymous subroutine, or a reference to a subroutine. .SH "BUGS" .IX Header "BUGS" Because it is used for overloading, the per-package hash \f(CW%OVERLOAD\fR now has a special meaning in Perl. The symbol table is filled with names looking like line\-noise. .PP For the purpose of inheritance every overloaded package behaves as if \&\f(CW\*(C`fallback\*(C'\fR is present (possibly undefined). This may create interesting effects if some package is not overloaded, but inherits from two overloaded packages. .PP Relation between overloading and \fItie()\fRing is broken. Overloading is triggered or not basing on the \fIprevious\fR class of \fItie()\fRd value. .PP This happens because the presence of overloading is checked too early, before any \fItie()\fRd access is attempted. If the \s-1\fIFETCH\s0()\fRed class of the \&\fItie()\fRd value does not change, a simple workaround is to access the value immediately after \fItie()\fRing, so that after this call the \fIprevious\fR class coincides with the current one. .PP \&\fBNeeded:\fR a way to fix this without a speed penalty. .PP Barewords are not covered by overloaded string constants. .PP This document is confusing. There are grammos and misleading language used in places. It would seem a total rewrite is needed.