Friday, December 5, 2008

Object oriented development with Perl

This sample code demonstrates how to implement operator overloading with Perl.
#!/usr/bin/perl -w
use strict;

my $n = new Number(5);
$n = $n + 1 - 2;

print "$n\n";

# The class implementation
package Number;

use overload '+' => \&add;
use overload '-' => \&subtract;
use overload '""' => \&toString;

sub new {
  my $class = shift;
  my $this = { size => shift };
  return bless ($this, $class);
}

sub subtract {
  my ($this, $v) = @_;

  $this->{'size'} -= $v;
  return $this;
}

sub add {
  my ($this, $v) = @_;

  $this->{'size'} += $v;
  return $this;
}

sub toString {
  my ($this) = @_;

  return "Summary " . $this->{'size'};
}