Perl Module Basics
Binary Operators
Most of the overloadable operators are binary operators. To implement a binary 
operator, you provide a method that takes three arguments. The first argument is 
always the overloaded object. The second is the other argument to the operator 
it might be another object or a plain scalar. The third argument gives you infor 
mation about the order of the arguments. When the third argument is true the
arguments are in the same position as in the operation that generated the call; 
when it is false, the arguments are reversed.
Why do you need this third argument? Consider implementing subtraction. 
These lines will generate the same method call if $number is an object in a class that 
overloads subtraction with a method called subtract():
$result = $number   7;   # actually $number >subtract(7, 0);
$result = 7   $number;   # actually $number >subtract(7, 1);
By examining the third argument, the implementation for subtract can do the 
right thing:
sub subtract {
  my ($self, $other, $reversed) = @_;
  if ($reversed) {
    return $other   $$self;
  } else {
    return $$self 
  $other;
  }
}
Of course, this assumes that your module will obey the normal rules of arithmetic; 
it doesn't have to!
Your binary operators will need to be a little more complicated than the pre 
ceding simple example. Since the second argument to the operator could be a 
normal variable or another object, there needs to be logic to handle both cases. 
Also, a binary operator should function as a constructor so that the results of the 
operation are also members of the class. Here's an implementation of addition for 
the Even module that always produces even numbers, rounding up where 
necessary:
use overload  +  => "add";
sub add {
  my ($self, $other, $reversed) = @_;
  my $result;
53
53






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