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.[150] 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 ...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