snoofkin
snoofkin

Reputation: 8895

Overloading operators in perl

Assuming I have a blessed references / objects $a and $b, each internally stored as a hashref and have:

$a->{_x}
$b->{_x}

is it possible to overload the arithmetic operations so when I will do this:

my $c = $a + $b;

I will have a blessed reference $c with $c->{_x} equals to $a->{_x} + $b->{_x}??

Upvotes: 4

Views: 669

Answers (1)

Oleg V. Volkov
Oleg V. Volkov

Reputation: 22421

Of course. Just use your usual constructor for a new object of your desired class in overloaded sub for + and set it's value to that sum (or whatever else you want).

Assuming you have new constructor that takes initial value as argument, that'd be something along lines of:

sub plus {
   my $self = shift;
   my $right = (shift or 0);
   return MySuperNumberObject->new($self->{_x} + $right);
};

use overload '+' => \+

Upvotes: 7

Related Questions