home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam  

Book Home Programming PerlSearch this book

31.16. use overload

In the Number module:

package Number;
use overload "+" => \&myadd,
             "-" => \&mysub,
            "*=" => "multiply_by";
In your program:
use Number;
$a = new Number 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, "Overloading".

Library Navigation Links

Copyright © 2001 O'Reilly & Associates. All rights reserved.