8.169. overloadLets you substitute class methods or your own subroutines for standard Perl operators. For example, the code: package Number; use overload "+" => \add, "*=" => "muas"; declares function add for addition and method muas in the Number class (or one of its base classes) for the assignment form *= of multiplication. Arguments to use overload are key/value pairs, in which the key is the operation being overloaded, and the value is the function or method that is to be substituted. Legal values are values permitted inside a &{ ... } call, so a subroutine name, a subroutine reference, or an anonymous subroutine are all legal. Legal keys (overloadable operations) are:
The functions specified with the use overload directive are typically called with three arguments. If the corresponding operation is binary, then the first two arguments are the two arguments of the operation. However, the first argument should always be an object in the package, so in some cases, the order of the arguments will be interchanged before the method is called. The third argument provides information on the order and can have these values:
Unary operations are considered binary operations with the second argument undefined. The special nomethod key should be followed by a reference to a function of four parameters and called when the overloading mechanism cannot find a method for an operation. The first three arguments are the arguments for the corresponding method if it was found; the fourth argument is the symbol corresponding to the missing method. If several methods are tried, the last one is used. For example, 1-$a can be equivalent to: &nomethodMethod($a, 1, 1, "-") if the pair "nomethod" => "nomethodMethod" was specified in the use overload directive. The special fallback key governs what to do if a method for a particular operation is not found. There are three possible cases, depending on the value associated with the fallback key:
The overload module provides the following public functions.
overload::Method(obj, op) Returns the undefined value or a reference to the method that implements op.
overload::Overloaded(arg) Returns true if arg is subject to overloading of some operations.
overload::StrVal(arg) Gives string value of arg if stringify overloading is absent. Copyright © 2002 O'Reilly & Associates. All rights reserved. |
|