Overload Handlers
When an overloaded operator is, er, operated, the
corresponding handler is invoked with three arguments. The first two
arguments are the two operands. If the operator only uses one operand,
the second argument is undef
.
The third argument indicates whether the first two arguments were swapped. Even under the rules of normal arithmetic, some operations, like addition or multiplication, don't usually care about the order of their arguments, but others, like subtraction and division, do.[1] Consider the difference between:
$object - 6
and:
6 - $object
If the first two arguments to a handler have been
swapped, the third argument will be true. Otherwise, the third
argument will be false, in which case there is a finer distinction as
well: if the handler has been triggered by another handler involving
assignment (as in +=
using +
to
figure out how to add), then the third argument is not merely false,
but undef
. This distinction enables some
optimizations.
As an example, here is a class that lets you manipulate a
bounded range of numbers. It overloads both +
and
-
so that the result of adding or subtracting
objects constrains the values within the range 0 and 255:
package ClipByte;use overload '+' => \&clip_add, '-' => \&clip_sub; sub new { my $class = shift; my $value = shift; return bless \$value => $class; } sub clip_add { my ($x, $y) = @_; my ($value) = ref($x) ? $$x : $x; $value += ref($y) ? $$y : $y; $value = 255 if $value > 255; $value = 0 if $value < 0; return bless ...
Get Programming Perl, 3rd Edition 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.