overload
Lets you substitute class methods or your own subroutines for standard Perl operators. For example, the code:
package Number;
use overload
"+" => \add,
"*=" => "muas";declares function 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, in which 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 | |
Increment, decrement | |
Transcendental | |
Boolean, string, numeric conversion | |
Special | |
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:
- False (
0) The order of arguments is as in the current operation.
- True ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access