Skip to Content
Programming Perl, 3rd Edition
book

Programming Perl, 3rd Edition

by Larry Wall, Tom Christiansen, Jon Orwant
July 2000
Intermediate to advanced
1104 pages
35h 1m
English
O'Reilly Media, Inc.
Content preview from Programming Perl, 3rd Edition

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 ...
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.
Start your free trial

You might also like

Programming Perl, 4th Edition

Programming Perl, 4th Edition

Tom Christiansen, brian d foy, Larry Wall, Jon Orwant
Learning Perl, 7th Edition

Learning Perl, 7th Edition

Randal L. Schwartz, brian d foy, Tom Phoenix
Programming the Perl DBI

Programming the Perl DBI

Tim Bunce, Alligator Descartes

Publisher Resources

ISBN: 0596000278Supplemental ContentErrata