overload
In the Number module:
package Number;
use overload "+" => \&myadd,
"–" => \&mysub,
"*=" => "multiply_by";In your program:
use Number; $a = Number–>new( 57 ); $b = $a + 5;
The built-in operators work well on strings and numbers, but make
little sense when applied to object references (since, unlike C or C++,
Perl doesn’t allow pointer arithmetic). The overload pragma lets you redefine the meanings
of these built-in operations when applied to objects of your own design.
In the previous example, the call to the pragma redefines three operations
on Number objects:
addition will call the Number::myadd
function, subtraction will call the Number::mysub function, and the
multiplicative assignment operator will call the multiply_by method in class Number (or one of its base classes). We say of
these operators that they are now overloaded because they have additional
meanings overlaid on them (and not because they have too many
meanings—though that may also be the case).
For much more on overloading, see Chapter 13.
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