Lets you substitute class methods or your own subroutines for standard Perl operators. For example, the code:
declares functionpackage Number; use overload "+" => \add, "*=" => "muas";
add
for addition and method
muas
in the Number class (or one of its base classes) for
the assignment form *=
of multiplication.Arguments to use overload
are key/value pairs,
where the key is the operation being overloaded, and the value is
the function or method that is to be substituted. Legal values
are values permitted inside a &{ ... }
call, so a
subroutine name, a subroutine reference, or an anonymous subroutine are
all legal. Legal keys (overloadable operations) are:
Type | Operations |
---|---|
Arithmetic |
|
Comparison |
|
Bit and unary | % ^ | neg ! ~ |
Increment, decrement | ++ - |
Transcendental | atan2 cos sin exp abs log sqrt |
Boolean, string, numeric conversion |
|
Special | nomethod fallback = |
The functions specified with the use overload
directive are
typically called with three arguments. If the corresponding operation is
binary, then the first two arguments are the two arguments of the operation.
However, the first argument should
always be an object in the package, so in some cases, the order
of the arguments will be interchanged before the method is called. The
third argument provides information on the order and can have these
values:
0
)The order of arguments is as in the current operation.
1
)The arguments are reversed.
The current operation is an assignment variant, but the usual function is called instead.
Unary operations are considered binary operations with the second argument undefined.
The special nomethod
key should be followed by a reference to a
function of four parameters and called when the overloading
mechanism cannot find a method for some operation. The first three arguments
are 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.
For example, 1-$a
can be equivalent to:
if the pair&nomethodMethod($a, 1, 1, "-")
"nomethod"
=>
"nomethodMethod"
was specified
in the use overload
directive.The special fallback
key governs what to do if a method for a
particular operation is not found. There are three possible cases,
depending on the value associated with the fallback
key:
Tries to use a substituted method.
If that fails, it tries to call the method
specified for nomethod
; if that also fails, an exception is raised.
The same as undefined, but no exception is raised. Instead, Perl silently reverts to non-overloaded operation.
Tries to call the method specified
for nomethod
; if that fails, an exception is raised.
The overload module provides the following public functions:
Copyright © 2001 O'Reilly & Associates. All rights reserved.