Perl Module Basics
Using method auto generation generally requires that your module follow the
normal rules of arithmetic. For example, if abs() is to be successfully generated by
< and subtraction, your module will have to have fairly standard semantics.
You can provide your own auto generation rules by overloading the special
nomethod key. The method will receive four arguments the normal three asso
ciated with binary operators (whether the called operator is binary or not), and a
fourth argument containing the operator actually called.
Finally, you can turn off auto generation altogether by setting the special
overload key fallback to 0 (although nomethod will still be tried if it exists). Alter
nately you can set it to 1 to allow an unavailable overload method to be ignored
Perl will continue with whatever behavior it would have had if overloading had not
been used at all. The default setting for fallback, undef, produces an error if an
overloaded operation cannot be found.
Overloading = It's Not What You Think
Overloading = does not overload assignment. What overloading = does do is
provide a copy constructor. For example, consider a class called Fraction that uses
an array
17
of two elements to represent a fraction internally and provides all the
normal overloaded math operators. Imagine it also provides an overloaded copy
constructor with the copy() method. Here's an example showing how the copy
constructor is used:
$x = Fraction >new(1, 2); # create a new Fraction containing one half (1/2).
$y = $x; # assign the reference in $x to $y. At this point
# both $x and $y reference the same object.
$x *= 4; # first implicitely calls the copy
# constructor: $x = $x >copy()
# then multiplies $x by 2 yielding 4/2
print "x = $x\n"; # prints x = 4/2
print "y = $y\n"; # prints y = 1/2
As you can see, the copy constructor is called implicitly before a mutating operator
is used, not when the assignment operator is used. If Fraction did not provide an
overloaded copy constructor, then this code would generate an error:
Operation = : no method found, argument in overloaded package Fraction
17. It's important that this class be implemented using something other than a scalar because
overload will actually auto generate a copy constructor for scalars.
55
55
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Inexpensive Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Jsp Hosting
Cheap Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved