In the Number module:
In your program:package Number; use overload "+" => \&myadd, "-" => \&mysub, "*=" => "multiply_by";
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).use Number; $a = new Number 57; $b = $a + 5;
For much more on overloading, see Chapter 13, "Overloading".
Copyright © 2002 O'Reilly & Associates. All rights reserved.