Chapter 2
Implementing a copy constructor is usually a simple matter of pulling out the 
values needed for initialization and calling new() to create a new object. In this 
case the object stores the numerator and denominator in the first and second 
positions of the object array so the copy constructor is written as follows:
package Fraction;
use overload  =  => "copy";
sub copy {
  my $self = shift;
  return ref($self) >new($self >[0], $self >[1]);
}
The copy constructor is only activated for the mutating operators: ++,   , +=,
and so on. If your object can have its value changed in other ways through a 
method call or by a nonmutating operator, for example then the user will need to 
call the copy constructor directly. In practice, this restriction makes the copy con 
structor suitable only for rather normal mathematical packages. If your module is 
playing outside the bounds of Perl's normal math, then it's probably not going to 
mesh well with an overloaded =.
Just to drive home the point that you're not overloading assignment, note that 
the copy constructor is never called if the object is the recipient of an assignment:
$object = 6;
After this assignment, $object contains the scalar  6  and is no longer a reference 
to an object, overloaded or not! If you really want to overload assignment, then 
what you need is a tied module. The next section will describe tied modules in all 
their glory.
Tied Modules
Tying enables a class to provide the implementation for a normal Perl variable. 
When a variable is tied to a class, all accesses to that variable are handled by 
methods in the class. This is similar to an overloaded class, but instead of returning a 
reference to a specially prepared object, tying enables a variable to be magically 
associated with a hidden object. This may sound complicated, but the implemen 
tation is quite simple all the hard stuff is handled by Perl.
56






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

web hosting perl

 

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