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, 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:

TypeOperations
Arithmetic

+ - * / % ** << >> x . += -= *= /= %= **= <<= >>= x= .=

Comparison

< <= > >= == != <=> lt le gt ge eq ne cmp

Bit and unary % ^ | neg ! ~
Increment, decrement ++ -
Transcendental atan2 cos sin exp abs log sqrt

Boolean, string, numeric conversion

bool "" 0+

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:

false (0)

The order of arguments is as in the current ...

Get Perl in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.