perlfunc
root
<P>
overload - Package for overloading perl operations
<P>
<HR>
<P>
<PRE> package SomeThing;
</PRE>
<P>
<PRE> use overload
'+' => \&myadd,
'-' => \&mysub;
# etc
...
</PRE>
<P>
<PRE> package main;
$a = new SomeThing 57;
$b=5+$a;
...
if (overload::Over
<P>
<HR>
<H2><A NAME="Declaration_of_overloaded_functi">Declaration of overloaded functions</A></H2>
<P>
The compilation directive
<P>
<PRE> package Number;
use overload
"+" => \&add,
"*=" => "muas";
</PRE>
<P>
declares function Number::add() for addition, and method
<CODE>muas()</CODE> in the ``class'' <CODE>Number</CODE> (or one of its base classes) for the assignment form <CODE>*=</CODE> of multiplication.
<P>
Arguments of this directive come in (key, value) pairs. Legal values are
values legal inside a <CODE>&{ ... }</CODE> 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.
<P>
The subroutine <CODE>add</CODE> will be called to execute <CODE>$a+$b</CODE> if <CODE>$a</CODE> is a reference to an object blessed into the package <CODE>Number</CODE>, or if <CODE>$a</CODE> is not an object from a package with defined
mathemagic addition, but <CODE>$b</CODE> is a reference to a <CODE>Number</CODE>. It can also be called in other situations, like
<CODE>$a+=7</CODE>, or <CODE>$a++</CODE>. See <A HREF="#MAGIC_AUTOGENERATION">MAGIC AUTOGENERATION</A>. (Mathemagical methods refer to methods triggered by an overloaded
mathematical operator.)
<P>
Since overloading respects inheritance via the <CODE>@ISA</CODE> hierarchy,
the above declaration would also trigger overloading of <CODE>+</CODE> and <CODE>*=</CODE> in all the packages which inherit from <CODE>Number</CODE>.
<P>
<HR>
<H2><A NAME="Calling_Conventions_for_Binary_O">Calling Conventions for Binary Operations</A></H2>
<P>
The functions specified in the <CODE>use overload ...</CODE> directive are called with three (in one particular case with four, see <A HREF="#Last_Resort">Last Resort</A>) 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 <CODE>7+$a</CODE>, 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:
<DL>
<DT><STRONG><A NAME="item_FALSE">FALSE</A></STRONG><P>
<DD>
the order of arguments is as in the current operation.
<P><DT><STRONG><A NAME="item_TRUE">TRUE</A></STRONG><P>
<DD>
the arguments are reversed.
<P><DT><STRONG><A NAME="item_undef">undef</A></STRONG><P>
<DD>
the current operation is an assignment variant (as in
<CODE>$a+=7</CODE>), but the usual function is called instead. This additional information
can be used to generate some optimizations. Compare
<A HREF="#Calling_Conventions_for_Mutators">Calling Conventions for Mutators</A>.
</DL>
<P>
<HR>
<H2><A NAME="Calling_Conventions_for_Unary_Op">Calling Conventions for Unary Operations</A></H2>
<P>
Unary operation are considered binary operations with the second argument
being [perlfunc:undef|undef]. Thus the functions that overloads <CODE>{"++"}</CODE>
is called with arguments <CODE>($a,undef,'')</CODE> when $a++ is executed.
<P>
<HR>
<H2><A NAME="Calling_Conventions_for_Mutators">Calling Conventions for Mutators</A></H2>
<P>
Two types of mutators have different calling conventions:
<DL>
<DT><STRONG><A NAME="item__">++ and --</A></STRONG><P>
<DD>
The routines which implement these operators are expected to actually
<EM>mutate</EM> their arguments. So, assuming that <CODE>$obj</CODE> is a reference to a
number,
<P>
<PRE> sub incr { my $n = $ {$_[0]}; ++$n; $_[0] = bless \$n}
</PRE>
<P>
is an appropriate implementation of overloaded <CODE>++</CODE>. Note that
<P>
<PRE> sub incr { ++$ {$_[0]} ; shift }
</PRE>
<P>
is
<FONT SIZE=-1>OK</FONT> if used with preincrement and with postincrement.
(In the case of postincrement a copying will be performed, see <A HREF="#Copy_Constructor">Copy Constructor</A>.)
<P><DT><STRONG><A NAME="item_x">x= and other assignment versions</A></STRONG><P>
<DD>
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.
<P>
This allows for the same method to be used as averloaded <CODE>+=</CODE> and
<CODE>+</CODE>. Note that this is <EM>allowed</EM>, but not recommended, since by the semantic of <A HREF="#Fallback">Fallback</A> Perl will call the method for <CODE>+</CODE> anyway, if <CODE>+=</CODE> is not overloaded.
</DL>
<P>
<STRONG>Warning.</STRONG> Due to the presense of assignment versions of operations, routines which
may be called in assignment context may create self-referencial structures.
Currently Perl will not free self-referential structures until cycles are <CODE>explicitly</CODE> broken. You may get problems when traversing your structures too.
<P>
Say,
<P>
<PRE> use overload '+' => sub { bless [ \$_[0], \$_[1] ] };
</PRE>
<P>
is asking for trouble, since for code <CODE>$obj += $foo</CODE> the subroutine is called as <CODE>$obj = add($obj, $foo, undef)</CODE>, or <CODE>$obj = [\$obj,
\$foo]</CODE>. If using such a subroutine is an important optimization, one can overload <CODE>+=</CODE> explicitly by a non-``optimized'' version, or switch to non-optimized
version if <CODE>not defined $_[2]</CODE> (see
<A HREF="#Calling_Conventions_for_Binary_O">Calling Conventions for Binary Operations</A>).
<P>
Even if no <EM>explicit</EM> assignment-variants of operators are present in the script, they may be
generated by the optimizer. Say, <CODE>",$obj,"</CODE> or
<CODE>',' . $obj . ','</CODE> may be both optimized to
<P>
<PRE> my $tmp = ',' . $obj; $tmp .= ',';
</PRE>
<P>
<HR>
<H2><A NAME="Overloadable_Operations">Overloadable Operations</A></H2>
<P>
The following symbols can be specified in <CODE>use overload</CODE> directive:
<UL>
<LI><STRONG><A NAME="item_Arithmetic">Arithmetic operations</A></STRONG>
<P>
<PRE> "+", "+=", "-", "-=", "*", "*=", "/", "/=", "%", "%=",
"**", "**=", "<<", "<<=", ">>", ">>=", "x", "x=", ".", ".=",
</PRE>
<P>
For these operations a substituted non-assignment variant can be called if
the assignment variant is not available. Methods for operations ``<CODE>+</CODE>'', ``<CODE>-</CODE>'', ``<CODE>+=</CODE>'', and ``<CODE>-=</CODE>'' can be called to automatically generate increment and decrement methods.
The operation ``<CODE>-</CODE>'' can be used to autogenerate missing methods for unary minus or [perlfunc:abs|abs].
<P>
See <A HREF="#MAGIC_AUTOGENERATION">MAGIC AUTOGENERATION</A>, <A HREF="#Calling_Conventions_for_Mutators">Calling Conventions for Mutators</A> and
<A HREF="#Calling_Conventions_for_Binary_O">Calling Conventions for Binary Operations</A>) for details of these substitutions.
<P><LI><STRONG><A NAME="item_Comparison">Comparison operations</A></STRONG>
<PRE> "<", "<=", ">", ">=", "==", "!=", "<=>",
"lt", "le", "gt", "ge", "eq", "ne", "cmp",
</PRE>
<P>
If the corresponding ``spaceship'' variant is available, it can be used to
substitute for the missing operation. During [perlfunc:sort|sort]ing arrays, <CODE>cmp</CODE> is used to compare values subject to <CODE>use overload</CODE>.
<P><LI><STRONG><A NAME="item_Bit">Bit operations</A></STRONG>
<PRE> "&", "^", "|", "neg", "!", "~",
</PRE>
<P>
``<CODE>neg</CODE>'' stands for unary minus. If the method for <CODE>neg</CODE> is not specified, it can be autogenerated using the method for subtraction.
If the method for ``<CODE>!</CODE>'' is not specified, it can be autogenerated using the methods for ``<CODE>bool</CODE>'', or ``<CODE>\"\"</CODE>'', or ``<CODE>0+</CODE>''.
<P><LI><STRONG><A NAME="item_Increment">Increment and decrement</A></STRONG>
<PRE> "++", "--",
</PRE>
<P>
If undefined, addition and subtraction methods can be used instead. These
operations are called both in prefix and postfix form.
<P><LI><STRONG><A NAME="item_Transcendental">Transcendental functions</A></STRONG>
<PRE> "atan2", "cos", "sin", "exp", "abs", "log", "sqrt",
</PRE>
<P>
If [perlfunc:abs|abs] is unavailable, it can be autogenerated using methods for ``<'' or
``<=>'' combined with either unary minus or subtraction.
<P><LI><STRONG><A NAME="item_Boolean">Boolean, string and numeric conversion</A></STRONG>
<PRE> "bool", "\"\"", "0+",
</PRE>
<P>
If one or two of these operations are unavailable, the remaining ones can
be used instead. <CODE>bool</CODE> is used in the flow control operators (like <CODE>while</CODE>) and for the ternary ``<CODE>?:</CODE>'' 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.
<P><LI><STRONG><A NAME="item_Special">Special</A></STRONG>
<PRE> "nomethod", "fallback", "=",
</PRE>
<P>
see <A HREF="#SPECIAL_SYMBOLS_FOR_C_use_overlo">SPECIAL SYMBOLS FOR <CODE>use overload</CODE></A>.
</UL>
<P>
See <A HREF="#Fallback">Fallback</A> for an explanation of when a missing method can be autogenerated.
<P>
<FONT SIZE=-1>A</FONT> computer-readable form of the above table is
available in the hash %overload::ops, with values being space-separated
lists of names:
<P>
<PRE> with_assign => '+ - * / % ** << >> x .',
assign => '+= -= *= /= %= **= <<= >>= x= .=',
str_comparison => '< <= > >= == !=',
'3way_comparison'=> '<=> cmp',
num_comparison => 'lt le gt ge eq ne',
binary => '& | ^',
unary => 'neg ! ~',
mutators => '++ --',
func => 'atan2 cos sin exp abs log sqrt',
conversion => 'bool "" 0+',
special => 'nomethod fallback ='
</PRE>
<P>
<HR>
<H2><A NAME="Inheritance_and_overloading">Inheritance and overloading</A></H2>
<P>
Inheritance interacts with overloading in two ways.
<DL>
<DT><STRONG><A NAME="item_Strings">Strings as values of use overload directive</A></STRONG><P>
<DD>
If <CODE>value</CODE> in
<P>
<PRE> use overload key => value;
</PRE>
<P>
is a string, it is interpreted as a method name.
<P><DT><STRONG><A NAME="item_Overloading">Overloading of an operation is inherited by derived classes</A></STRONG><P>
<DD>
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:
<P>
If <CODE>A</CODE> inherits from <CODE>B</CODE> and [perlman:perlop|perlop] (in this order), <CODE>B</CODE> overloads
<CODE>+</CODE> with <CODE>\&D::plus_sub</CODE>, and [perlman:perlop|perlop] overloads <CODE>+</CODE> by <CODE>"plus_meth"</CODE>, then the subroutine <CODE>D::plus_sub</CODE> will be called to implement operation <CODE>+</CODE> for an object in package <CODE>A</CODE>.
</DL>
<P>
Note that since the value of the <CODE>fallback</CODE> key is not a subroutine, its inheritance is not governed by the above
rules. In the current implementation, the value of <CODE>fallback</CODE> in the first overloaded ancestor is used, but this is accidental and
subject to change.
<P>
<HR>
<H1><A NAME="SPECIAL_SYMBOLS_FOR_C_use_overlo">SPECIAL SYMBOLS FOR <CODE>use overload</CODE></A></H1>
<P>
Three keys are recognized by Perl that are not covered by the above
description.
<P>
<HR>
<H2><A NAME="Last_Resort">Last Resort</A></H2>
<P>
<CODE>"nomethod"</CODE> 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, <CODE>1-$a</CODE> can be equivalent to
<P>
<PRE> &nomethodMethod($a,1,1,"-")
</PRE>
<P>
if the pair <CODE>"nomethod" => "nomethodMethod"</CODE> was specified in the
<CODE>use overload</CODE> directive.
<P>
If some operation cannot be resolved, and there is no function assigned to <CODE>"nomethod"</CODE>, then an exception will be raised via
<CODE>die()--</CODE> unless <CODE>"fallback"</CODE> was specified as a key in <CODE>use overload</CODE> directive.
<P>
<HR>
<H2><A NAME="Fallback">Fallback</A></H2>
<P>
The key <CODE>"fallback"</CODE> governs what to do if a method for a particular operation is not found.
Three different cases are possible depending on the value of <CODE>"fallback"</CODE>:
<UL>
<LI><STRONG>undef</STRONG>
<P>
Perl tries to use a substituted method (see <A HREF="#MAGIC_AUTOGENERATION">MAGIC AUTOGENERATION</A>). If this fails, it then tries to calls <CODE>"nomethod"</CODE> value; if missing, an exception will be raised.
<P><LI><STRONG>TRUE</STRONG>
The same as for the [perlfunc:undef|undef] value, but no exception is raised. Instead, it silently reverts to what it
would have done were there no <CODE>use overload</CODE>
present.
<P><LI><STRONG><A NAME="item_defined">defined, but FALSE</A></STRONG>
No autogeneration is tried. Perl tries to call
<CODE>"nomethod"</CODE> value, and if this is missing, raises an exception.
</UL>
<P>
<STRONG>Note.</STRONG> <CODE>"fallback"</CODE> inheritance via <CODE>@ISA</CODE> is not carved in stone yet, see <A HREF="#Inheritance_and_overloading">Inheritance and overloading</A>.
<P>
<HR>
<H2><A NAME="Copy_Constructor">Copy Constructor</A></H2>
<P>
The value for <CODE>"="</CODE> is a reference to a function with three arguments, i.e., it looks like the
other values in <CODE>use
overload</CODE>. However, it does not overload the Perl assignment operator. This would go
against Camel hair.
<P>
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
<P>
<PRE> $a=$b;
++$a;
</PRE>
<P>
To make this change <CODE>$a</CODE> and not change $b, a copy of <CODE>$$a</CODE> is made, and <CODE>$a</CODE> is assigned a reference to this new object.
This operation is done during execution of the <CODE>++$a</CODE>, and not during the assignment, (so before the increment <CODE>$$a</CODE> coincides with <CODE>$$b</CODE>). This is only done if <CODE>++</CODE> is expressed via a method for <CODE>'++'</CODE> or <CODE>'+='</CODE> (or
<CODE>nomethod</CODE>). Note that if this operation is expressed via <CODE>'+'</CODE>
a nonmutator, i.e., as in
<P>
<PRE> $a=$b;
$a=$a+1;
</PRE>
<P>
then <CODE>$a</CODE> does not reference a new copy of <CODE>$$a</CODE>, since <CODE>$$a</CODE> does not appear as lvalue when the above code is
executed.
<P>
If the copy constructor is required during the execution of some mutator,
but a method for <CODE>'='</CODE> was not specified, it can be autogenerated as a string copy if the object
is a plain scalar.
<DL>
<DT><STRONG><A NAME="item_Example">Example</A></STRONG><P>
<DD>
The actually executed code for
<P>
<PRE> $a=$b;
Something else which does not modify $a or $b....
++$a;
</PRE>
<P>
may be
<P>
<PRE> $a=$b;
Something else which does not modify $a or $b....
$a = $a->clone(undef,"");
$a->incr(undef,"");
</PRE>
<P>
if <CODE>$b</CODE> was mathemagical, and <CODE>'++'</CODE> was overloaded with <CODE>\&incr</CODE>,
<CODE>'='</CODE> was overloaded with <CODE>\&clone</CODE>.
</DL>
<P>
Same behaviour is triggered by <CODE>$b = $a++</CODE>, which is consider a synonim for
<CODE>$b = $a; ++$a</CODE>.
<P>
<HR>
<H1><A NAME="MAGIC_AUTOGENERATION">MAGIC AUTOGENERATION</A></H1>
<P>
If a method for an operation is not found, and the value for <CODE>"fallback"</CODE> is
<FONT SIZE=-1>TRUE</FONT> 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:
<DL>
<DT><STRONG><A NAME="item_Assignment">Assignment forms of arithmetic operations</A></STRONG><P>
<DD>
<CODE>$a+=$b</CODE> can use the method for <CODE>"+"</CODE> if the method for <CODE>"+="</CODE>
is not defined.
<P><DT><STRONG><A NAME="item_Conversion">Conversion operations</A></STRONG><P>
<DD>
String, numeric, and boolean conversion are calculated in terms of one
another if not all of them are defined.
<P><DT><STRONG><A NAME="item_Increment">Increment and decrement</A></STRONG><P>
<DD>
The <CODE>++$a</CODE> operation can be expressed in terms of <CODE>$a+=1</CODE> or <CODE>$a+1</CODE>, and <CODE>$a--</CODE> in terms of <CODE>$a-=1</CODE> and <CODE>$a-1</CODE>.
<P><DT><STRONG><A NAME="item_abs">abs($a)</A></STRONG><P>
<DD>
can be expressed in terms of <CODE>$a<0</CODE> and <CODE>-$a</CODE> (or <CODE>0-$a</CODE>).
<P><DT><STRONG><A NAME="item_Unary">Unary minus</A></STRONG><P>
<DD>
can be expressed in terms of subtraction.
<P><DT><STRONG><A NAME="item_Negation">Negation</A></STRONG><P>
<DD>
<CODE>!</CODE> and <CODE>not</CODE> can be expressed in terms of boolean conversion, or string or numerical
conversion.
<P><DT><STRONG><A NAME="item_Concatenation">Concatenation</A></STRONG><P>
<DD>
can be expressed in terms of string conversion.
<P><DT><STRONG><A NAME="item_Comparison">Comparison operations</A></STRONG><P>
<DD>
can be expressed in terms of its ``spaceship'' counterpart: either
<CODE><=></CODE> or <CODE>cmp</CODE>:
<P>
<PRE> <, >, <=, >=, ==, != in terms of <=>
lt, gt, le, ge, eq, ne in terms of cmp
</PRE>
<DT><STRONG><A NAME="item_Copy">Copy operator</A></STRONG><P>
<DD>
can be expressed in terms of an assignment to the dereferenced value, if
this value is a scalar and not a reference.
</DL>
<P>
<HR>
<H1><A NAME="Losing_overloading">Losing overloading</A></H1>
<P>
The restriction for the comparison operation is that even if, for example,
`<CODE>cmp</CODE>' should return a blessed reference, the autogenerated `<CODE>lt</CODE>' function will produce only a standard logical value based on the
numerical value of the result of `<CODE>cmp</CODE>'. In particular, a working numeric conversion is needed in this case
(possibly expressed in terms of other conversions).
<P>
Similarly, <CODE>.=</CODE> and <CODE>x=</CODE> operators lose their mathemagical properties if the string conversion
substitution is applied.
<P>
When you
<CODE>chop()</CODE> a mathemagical object it
is promoted to a string and its mathemagical properties are lost. The same
can happen with other operations as well.
<P>
<HR>
<H1><A NAME="Run_time_Overloading">Run-time Overloading</A></H1>
<P>
Since all [perlfunc:use|use] directives are executed at compile-time, the only way to change overloading
during run-time is to
<P>
<PRE> eval 'use overload "+" => \&addmethod';
</PRE>
<P>
You can also use
<P>
<PRE> eval 'no overload "+", "--", "<="';
</PRE>
<P>
though the use of these constructs during run-time is questionable.
<P>
<HR>
<H1><A NAME="Public_functions">Public functions</A></H1>
<P>
Package <CODE>overload.pm</CODE> provides the following public functions:
<DL>
<DT><STRONG><A NAME="item_overload">overload::StrVal(arg)</A></STRONG><P>
<DD>
Gives string value of <CODE>arg</CODE> as in absence of stringify overloading.
<P><DT><STRONG><A NAME="item_overload">overload::Overloaded(arg)</A></STRONG><P>
<DD>
Returns true if <CODE>arg</CODE> is subject to overloading of some operations.
<P><DT><STRONG><A NAME="item_overload">overload::Method(obj,op)</A></STRONG><P>
<DD>
Returns [perlfunc:undef|undef] or a reference to the method that implements <CODE>op</CODE>.
</DL>
<P>
<HR>
<H1><A NAME="Overloading_constants">Overloading constants</A></H1>
<P>
For some application Perl parser mangles constants too much. It is possible
to hook into this process via overload::constant() and
overload::remove_constant() functions.
<P>
These functions take a hash as an argument. The recognized keys of this
hash are
<DL>
<DT><STRONG><A NAME="item_integer">integer</A></STRONG><P>
<DD>
to overload integer constants,
<P><DT><STRONG><A NAME="item_float">float</A></STRONG><P>
<DD>
to overload floating point constants,
<P><DT><STRONG><A NAME="item_binary">binary</A></STRONG><P>
<DD>
to overload octal and hexadecimal constants,
<P><DT><STRONG><A NAME="item_q">q</A></STRONG><P>
<DD>
to overload [perlman:perlop|perlop]-quoted strings, constant pieces of [perlman:perlop|perlop]- and [perlman:perlop|perlop]-quoted strings and here-documents,
<P><DT><STRONG><A NAME="item_qr">qr</A></STRONG><P>
<DD>
to overload constant pieces of regular expressions.
</DL>
<P>
The corresponding values are references to functions which take three
arguments: the first one is the <EM>initial</EM> 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 [perlman:perlop|perlop]- and [perlman:perlop|perlop]- constants, it is [perlman:perlop|perlop] in single-quote context (comes from strings, regular expressions, and single-quote
<FONT SIZE=-1>HERE</FONT> documents), it is
[perlman:perlop|perlop] for arguments of [perlman:perlop|perlop]/[perlman:perlop|perlop] operators, it is [perlman:perlop|perlop] for right-hand side of [perlman:perlop|perlop]-operator, and it is [perlman:perlop|perlop] otherwise.
<P>
Since an expression <CODE>"ab$cd,,"</CODE> is just a shortcut for <CODE>'ab' . $cd . ',,'</CODE>, 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.
<P>
Note that it is probably meaningless to call the functions overload::constant() and overload::remove_constant() from anywhere but
<CODE>import()</CODE> and
<CODE>unimport()</CODE> methods. From these methods they may be called as
<P>
<PRE> sub import {
shift;
return unless @_;
die "unknown import: @_" unless @_ == 1 and $_[0] eq ':constant';
overload::constant integer => sub {Math::BigInt->new(shift)};
}
</PRE>
<P>
<STRONG>BUGS</STRONG> Currently overloaded-ness of constants does not propagate into [perlfunc:eval|eval].
<P>
<HR>
<H1><A NAME="IMPLEMENTATION">IMPLEMENTATION</A></H1>
<P>
What follows is subject to change
<FONT SIZE=-1>RSN.</FONT>
<P>
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 <CODE>use overload</CODE>, <CODE>no overload</CODE>, new function definitions, and changes in
<FONT SIZE=-1>@ISA.</FONT> However, this invalidation remains unprocessed
until the next [perlfunc:bless|bless]ing into the package. Hence if you want to change overloading structure
dynamically, you'll need an additional (fake) [perlfunc:bless|bless]ing to update the table.
<P>
(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 <CODE>%ENV</CODE> 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.)
<P>
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.
<P>
In fact, if <CODE>use overload</CODE> is not present, there is almost no overhead for overloadable operations, so most programs should not suffer measurable performance penalties.
<FONT SIZE=-1>A</FONT> 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
<CODE>use overload</CODE> and without it. So far there have been no reports of substantial speed
degradation if Perl is compiled with optimization turned on.
<P>
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 <EM>all</EM> the packages acquire a magic during the next [perlfunc:bless|bless]ing into the package. This magic is three-words-long for packages without
overloading, and carries the cache tabel if the package is overloaded.
<P>
Copying (<CODE>$a=$b</CODE>) is shallow; however, a one-level-deep copying is carried out before any
operation that can imply an assignment to the object <CODE>$a</CODE> (or
$b) refers to, like <CODE>$a++</CODE>. You can override this behavior by defining your own copy constructor (see <A HREF="#Copy_Constructor">Copy Constructor</A>).
<P>
It is expected that arguments to methods that are not explicitly supposed
to be changed are constant (but this is not enforced).
<P>
<HR>
<H1><A NAME="Metaphor_clash">Metaphor clash</A></H1>
<P>
One may wonder why the semantic of overloaded <CODE>=</CODE> is so counterintuive. If it <EM>looks</EM> counterintuive to you, you are subject to a metaphor clash.
<P>
Here is a Perl object metaphor:
<P>
<EM><PRE> object is a reference to blessed data
</PRE>
</EM>
<P>
and an arithmetic metaphor:
<P>
<EM><PRE> object is a thing by itself
</PRE>
</EM>.
<P>
The <EM>main</EM> problem of overloading <CODE>=</CODE> is the fact that these metaphors imply different actions on the assignment <CODE>$a = $b</CODE> if <CODE>$a</CODE> and <CODE>$b</CODE> are objects. Perl-think implies that
<CODE>$a</CODE> becomes a reference to whatever <CODE>$b</CODE> was
referencing. Arithmetic-think implies that the value of ``object''
<CODE>$a</CODE> is changed to become the value of the object $b, preserving
the fact that <CODE>$a</CODE> and <CODE>$b</CODE> are separate entities.
<P>
The difference is not relevant in the absence of mutators. After a Perl-way
assignment an operation which mutates the data referenced by
<CODE>$a</CODE> would change the data referenced by <CODE>$b</CODE> too.
Effectively, after
<CODE>$a = $b</CODE> values of <CODE>$a</CODE> and <CODE>$b</CODE> become <EM>indistinguishable</EM>.
<P>
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 not possible to freely mix two contradicting metaphors,
overloading allows the arithmetic way to write things <EM>as
far as all the mutators are called via overloaded access only</EM>. The way it is done is described in <A HREF="#Copy_Constructor">Copy Constructor</A>.
<P>
If some mutator methods are directly applied to the overloaded values, one
may need to <EM>explicitly unlink</EM> other values which references the same value:
<P>
<PRE> $a = new Data 23;
...
$b = $a; # $b is "linked" to $a
...
$a = $a->clone; # Unlink $b from $a
$a->increment_by(4);
</PRE>
<P>
Note that overloaded access makes this transparent:
<P>
<PRE> $a = new Data 23;
$b = $a; # $b is "linked" to $a
$a += 4; # would unlink $b automagically
</PRE>
<P>
However, it would not make
<P>
<PRE> $a = new Data 23;
$a = 4; # Now $a is a plain 4, not 'Data'
</PRE>
<P>
preserve ``objectness'' of $a. But Perl <EM>has</EM> a way to make assignments to an object do whatever you want. It is just not the overload, but
<CODE>tie()ing</CODE> interface (see
[perlfunc:tie|tie]). Adding a
<CODE>FETCH()</CODE> method which returns the object itself, and
<CODE>STORE()</CODE> method which changes the value of the object, one can reproduce the arithmetic metaphor in its completeness, at least for variables which were
<CODE>tie()d</CODE> from the start.
<P>
(Note that a workaround for a bug may be needed, see <A HREF="#BUGS">BUGS</A>.)
<P>
<HR>
<H1><A NAME="Cookbook">Cookbook</A></H1>
<P>
Please add examples to what follows!
<P>
<HR>
<H2><A NAME="Two_face_scalars">Two-face scalars</A></H2>
<P>
Put this in <EM>two_face.pm</EM> in your Perl library directory:
<P>
<PRE> package two_face; # Scalars with separate string and
# numeric values.
sub new { my $p = shift; bless [@_], $p }
use overload '""' => \&str, '0+' => \&num, fallback => 1;
sub num {shift->[1]}
sub str {shift->[0]}
</PRE>
<P>
Use it as follows:
<P>
<PRE> require two_face;
my $seven = new two_face ("vii", 7);
printf "seven=$seven, seven=%d, eight=%d\n", $seven, $seven+1;
print "seven contains `i'\n" if $seven =~ /i/;
</PRE>
<P>
(The second line creates a scalar which has both a string value, and a
numeric value.) This prints:
<P>
<PRE> seven=vii, seven=7, eight=8
seven contains `i'
</PRE>
<P>
<HR>
<H2><A NAME="Symbolic_calculator">Symbolic calculator</A></H2>
<P>
Put this in <EM>symbolic.pm</EM> in your Perl library directory:
<P>
<PRE> package symbolic; # Primitive symbolic calculator
use overload nomethod => \&wrap;
</PRE>
<P>
<PRE> sub new { shift; bless ['n', @_] }
sub wrap {
my ($obj, $other, $inv, $meth) = @_;
($obj, $other) = ($other, $obj) if $inv;
bless [$meth, $obj, $other];
}
</PRE>
<P>
This module is very unusual as overloaded modules go: it does not provide
any usual overloaded operators, instead it provides the <A HREF="#Last_Resort">Last Resort</A> operator <CODE>nomethod</CODE>. In this example the corresponding subroutine returns an object which
encupsulates operations done over the objects: <CODE>new symbolic 3</CODE> contains <CODE>['n', 3]</CODE>, <CODE>2 + new
symbolic 3</CODE> contains <CODE>['+', 2, ['n', 3]]</CODE>.
<P>
Here is an example of the script which ``calculates'' the side of
circumscribed octagon using the above package:
<P>
<PRE> require symbolic;
my $iter = 1; # 2**($iter+2) = 8
my $side = new symbolic 1;
my $cnt = $iter;
while ($cnt--) {
$side = (sqrt(1 + $side**2) - 1)/$side;
}
print "OK\n";
</PRE>
<P>
The value of <CODE>$side</CODE> is
<P>
<PRE> ['/', ['-', ['sqrt', ['+', 1, ['**', ['n', 1], 2]],
undef], 1], ['n', 1]]
</PRE>
<P>
Note that while we obtained this value using a nice little script, there is
no simple way to <EM>use</EM> this value. In fact this value may be inspected in debugger (see [perlman:perldebug|perldebug]), but ony if
<CODE>bareStringify</CODE> <STRONG>O</STRONG>ption is set, and not via <CODE>p</CODE> command.
<P>
If one attempts to print this value, then the overloaded operator
<CODE>""</CODE> will be called, which will call <CODE>nomethod</CODE> operator. The result of this operator will be stringified again, but this
result is again of type <CODE>symbolic</CODE>, which will lead to an infinite loop.
<P>
Add a pretty-printer method to the module <EM>symbolic.pm</EM>:
<P>
<PRE> 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]";
}
</PRE>
<P>
Now one can finish the script by
<P>
<PRE> print "side = ", $side->pretty, "\n";
</PRE>
<P>
The method <CODE>pretty</CODE> is doing object-to-string conversion, so it is natural to overload the
operator <CODE>""</CODE> using this method. However, inside such a method it is not necessary to
pretty-print the
<EM>components</EM> <CODE>$a</CODE> and <CODE>$b</CODE> of an object. In the above subroutine
<CODE>"[$meth $a $b]"</CODE> is a catenation of some strings and components <CODE>$a</CODE> and $b. If
these components use overloading, the catenation operator will look for an
overloaded operator <CODE>.</CODE>, if not present, it will look for an overloaded operator <CODE>""</CODE>. Thus it is enough to use
<P>
<PRE> use overload nomethod => \&wrap, '""' => \&str;
sub str {
my ($meth, $a, $b) = @{+shift};
$a = 'u' unless defined $a;
$b = 'u' unless defined $b;
"[$meth $a $b]";
}
</PRE>
<P>
Now one can change the last line of the script to
<P>
<PRE> print "side = $side\n";
</PRE>
<P>
which outputs
<P>
<PRE> side = [/ [- [sqrt [+ 1 [** [n 1 u] 2]] u] 1] [n 1 u]]
</PRE>
<P>
and one can inspect the value in debugger using all the possible methods.
<P>
Something is is still amiss: consider the loop variable <CODE>$cnt</CODE>
of the script. It was a number, not an object. We cannot make this value of
type <CODE>symbolic</CODE>, since then the loop will not terminate.
<P>
Indeed, to terminate the cycle, the <CODE>$cnt</CODE> should become false.
However, the operator <CODE>bool</CODE> for checking falsity is overloaded (this time via overloaded <CODE>""</CODE>), and returns a long string, thus any object of type <CODE>symbolic</CODE> 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.
<P>
Here is the text of <EM>symbolic.pm</EM> with such a routine added (and slightly modifed
<CODE>str()):</CODE>
<P>
<PRE> package symbolic; # Primitive symbolic calculator
use overload
nomethod => \&wrap, '""' => \&str, '0+' => \&num;
</PRE>
<P>
<PRE> 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);
}
</PRE>
<P>
All the work of numeric conversion is done in <CODE>%subr</CODE> and
<CODE>num().</CODE> Of course, <CODE>%subr</CODE> is not complete, it contains only operators used in teh example below. Here is the extra-credit question: why do we need an explicit recursion in
<CODE>num()?</CODE> (Answer is at the end of this section.)
<P>
Use this module like this:
<P>
<PRE> require symbolic;
my $iter = new symbolic 2; # 16-gon
my $side = new symbolic 1;
my $cnt = $iter;
while ($cnt) {
$cnt = $cnt - 1; # Mutator `--' not implemented
$side = (sqrt(1 + $side**2) - 1)/$side;
}
printf "%s=%f\n", $side, $side;
printf "pi=%f\n", $side*(2**($iter+2));
</PRE>
<P>
It prints (without so many line breaks)
<P>
<PRE> [/ [- [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
</PRE>
<P>
The above module is very primitive. It does not implement mutator methods (<CODE>++</CODE>, <CODE>-=</CODE> and so on), does not do deep copying (not required without mutators!), and
implements only those arithmetic operations which are used in the example.
<P>
To implement most arithmetic operattions is easy, one should just use the
tables of operations, and change the code which fills <CODE>%subr</CODE> to
<P>
<PRE> 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'\n";
$subr{$op} = eval "sub {$op shift()}";
}
</PRE>
<P>
Due to <A HREF="#Calling_Conventions_for_Mutators">Calling Conventions for Mutators</A>, we do not need anything special to make <CODE>+=</CODE> and friends work, except filling <CODE>+=</CODE> entry of %subr, and defining a copy constructor (needed since Perl has no
way to know that the implementation of <CODE>'+='</CODE> does not mutate the argument, compare <A HREF="#Copy_Constructor">Copy Constructor</A>).
<P>
To implement a copy constructor, add <CODE>'=' =</CODE> \&cpy> to <CODE>use overload</CODE>
line, and code (this code assumes that mutators change things one level
deep only, so recursive copying is not needed):
<P>
<PRE> sub cpy {
my $self = shift;
bless [@$self], ref $self;
}
</PRE>
<P>
To make <CODE>++</CODE> and <CODE>--</CODE> work, we need to implement actual mutators, either directly, or in <CODE>nomethod</CODE>. We continue to do things inside
<CODE>nomethod</CODE>, thus add
<P>
<PRE> if ($meth eq '++' or $meth eq '--') {
@$obj = ($meth, (bless [@$obj]), 1); # Avoid circular reference
return $obj;
}
</PRE>
<P>
after the first line of
<CODE>wrap().</CODE> This is not a most
effective implementation, one may consider
<P>
<PRE> sub inc { $_[0] = bless ['++', shift, 1]; }
</PRE>
<P>
instead.
<P>
As a final remark, note that one can fill <CODE>%subr</CODE> by
<P>
<PRE> 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{'-'};
</PRE>
<P>
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.
<P>
Here is the answer for the exercise: In the case of
<CODE>str(),</CODE> we need no explicit
recursion since the overloaded <CODE>.</CODE>-operator will fall back to an existing overloaded operator <CODE>""</CODE>. Overloaded arithmetic operators <EM>do not</EM> fall back to numeric conversion if <CODE>fallback</CODE> is not explicitly requested. Thus without an explicit recursion
<CODE>num()</CODE> would convert <CODE>['+', $a, $b]</CODE> to <CODE>$a + $b</CODE>, which would just rebuild the argument of
<CODE>num().</CODE>
<P>
If you wonder why defaults for conversion are different for
<CODE>str()</CODE> and
<CODE>num(),</CODE> 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 teh explicit recursion
<CODE>num()</CODE> is more fragile than
<CODE>sym():</CODE> we need to explicitly check for the type of <CODE>$a</CODE> and $b. If componets <CODE>$a</CODE> and <CODE>$b</CODE> happen to be of some related type, this may lead to problems.
<P>
<HR>
<H2><A NAME="I_Really_symbolic_calculator"><EM>Really</EM> symbolic calculator</A></H2>
<P>
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 <EM>used</EM>.
<P>
To see it in action, add a method
<P>
<PRE> sub STORE {
my $obj = shift;
$#$obj = 1;
@$obj->[0,1] = ('=', shift);
}
</PRE>
<P>
to the package <CODE>symbolic</CODE>. After this change one can do
<P>
<PRE> my $a = new symbolic 3;
my $b = new symbolic 4;
my $c = sqrt($a**2 + $b**2);
</PRE>
<P>
and the numeric value of <CODE>$c</CODE> becomes 5. However, after calling
<P>
<PRE> $a->STORE(12); $b->STORE(5);
</PRE>
<P>
the numeric value of <CODE>$c</CODE> becomes 13. There is no doubt now that
the module symbolic provides a <EM>symbolic</EM> calculator indeed.
<P>
To hide the rough edges under the hood, provide a
<CODE>tie()d</CODE> interface to the
package <CODE>symbolic</CODE> (compare with <A HREF="#Metaphor_clash">Metaphor clash</A>). Add methods
<P>
<PRE> sub TIESCALAR { my $pack = shift; $pack->new(@_) }
sub FETCH { shift }
sub nop { } # Around a bug
</PRE>
<P>
(the bug is described in <A HREF="#BUGS">BUGS</A>). One can use this new interface as
<P>
<PRE> tie $a, 'symbolic', 3;
tie $b, 'symbolic', 4;
$a->nop; $b->nop; # Around a bug
</PRE>
<P>
<PRE> my $c = sqrt($a**2 + $b**2);
</PRE>
<P>
Now numeric value of <CODE>$c</CODE> is 5. After <CODE>$a = 12; $b = 5</CODE> the numeric value of <CODE>$c</CODE> becomes 13. To insulate the user of
the module add a method
<P>
<PRE> sub vars { my $p = shift; tie($_, $p), $_->nop foreach @_; }
</PRE>
<P>
Now
<P>
<PRE> my ($a, $b);
symbolic->vars($a, $b);
my $c = sqrt($a**2 + $b**2);
</PRE>
<P>
<PRE> $a = 3; $b = 4;
printf "c5 %s=%f\n", $c, $c;
</PRE>
<P>
<PRE> $a = 12; $b = 5;
printf "c13 %s=%f\n", $c, $c;
</PRE>
<P>
shows that the numeric value of <CODE>$c</CODE> follows changes to the
values of <CODE>$a</CODE> and $b.
<P>
<HR>
<H1><A NAME="AUTHOR">AUTHOR</A></H1>
<P>
Ilya Zakharevich <<EM>ilya@math.mps.ohio-state.edu</EM>>.
<P>
<HR>
<H1><A NAME="DIAGNOSTICS">DIAGNOSTICS</A></H1>
<P>
When Perl is run with the <STRONG>-Do</STRONG> switch or its equivalent, overloading induces diagnostic messages.
<P>
Using the [perlman:perlop|perlop] command of Perl debugger (see [perlman:perldebug|perldebug]) one can deduce which operations are overloaded (and which ancestor
triggers this overloading). Say, if <CODE>eq</CODE> is overloaded, then the method <CODE>(eq</CODE>
is shown by debugger. The method <CODE>()</CODE> corresponds to the <CODE>fallback</CODE>
key (in fact a presence of this method shows that this package has
overloading enabled, and it is what is used by the <CODE>Overloaded</CODE>
function of module <CODE>overload</CODE>).
<P>
<HR>
<H1><A NAME="BUGS">BUGS</A></H1>
<P>
Because it is used for overloading, the per-package hash
<CODE>%OVERLOAD</CODE> now has a special meaning in Perl. The symbol table
is filled with names looking like line-noise.
<P>
For the purpose of inheritance every overloaded package behaves as if
<CODE>fallback</CODE> is present (possibly undefined). This may create interesting effects if
some package is not overloaded, but inherits from two overloaded packages.
<P>
Relation between overloading and
<CODE>tie()ing</CODE> is broken.
Overloading is triggered or not basing on the <EM>previous</EM> class of
<CODE>tie()d</CODE> value.
<P>
This happens because the presence of overloading is checked too early, before any
<CODE>tie()d</CODE> access is attempted. If the
<CODE>FETCH()ed</CODE> class of the
<CODE>tie()d</CODE> value does not change, a simple workaround is to access the value immediately after
<CODE>tie()ing,</CODE> so that after this call the
<EM>previous</EM> class coincides with the current one.
<P>
<STRONG>Needed:</STRONG> a way to fix this without a speed penalty.
<P>
Barewords are not covered by overloaded string constants.
<P>
This document is confusing. There are grammos and misleading language used
in places. It would seem a total rewrite is needed.
<HR>