The overload Pragma
The overload pragma implements operator overloading. You provide it with a key/value
list of operators and their associated behaviors:
package MyClass;
use overload "+" => \&myadd, # coderef
"<" => "less_than", # named method
"abs" => sub { return @_ }; # anonymous subroutineNow when you try to add two MyClass objects, the myadd subroutine will be called to create
the result.
When you try to compare two MyClass objects with the < operator, Perl notices that the
behavior is specified as a string and interprets the string as a
method name and not simply as a subroutine name. In the example above,
the less_than method might be
supplied by the MyClass package
itself or inherited from a base class of MyClass, but the myadd subroutine must be supplied by the
current package. The anonymous subroutine for abs
supplies itself even more directly. However these routines are
supplied, we’ll call them handlers.
For unary operators (those taking only one operand, like
abs), the handler specified for the
class is invoked whenever the operator is applied to an object of that
class.
For binary operators like + or <, the handler is invoked whenever the
first operand is an object of the class or when
the second operand is an object of the class and the first operand has
no overloading behavior. That’s so you can say either:
$object + 6
or:
6 + $object
without having to worry about the order of operands. (In the second case, the operands will be swapped when passed to the handler.) If our ...
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