package Pair; use strict; use warnings; use Carp; use overload '""' => \&string, '+' => \&add, '-' => \&subtract; #constructor sub new { my $class = shift; croak "Only 2 arguments to $class constructor allowed" unless @_ == 2; #The below is really doing three steps at once: # Creating an anonymous array reference, which contains the values passed to new() # Blessing this reference into $class # Returning the newly blessed object (as bless() returns the reference, and # all Perl blocks return the last statement evaluated bless [ @_ ], $class; } #accessors sub first { my $obj = shift; $obj->[0] = shift if @_; $obj->[0]; } sub second { my $obj = shift; $obj->[1] = shift if @_; $obj->[1]; } #stringification subroutine - elemements in parens, seperated by comma sub string { my $obj = shift; "($obj->[0], $obj->[1])"; } #addition overloading #if a Pair is added to another pair, the corresponding elements are summed #if a Pair is added to an integer, the integer is added to each element. sub add { my $obj = shift; my $arg = shift; if (ref $arg and $arg->isa(ref ($obj))){ #if second argument is another Pair: bless [$obj->[0] + $arg->[0], $obj->[1] + $arg->[1]], ref $obj; } else { #second argument is not a Pair bless [$obj->[0] + $arg, $obj->[1] + $arg], ref $obj; } } #subtraction overloading #this is more complicated. If a Pair is subtracted from another pair, the #corresponding elements are subtracted. #If an integer is subtracted from a Pair, that integer is subtracted from #each element of the Pair. #if a Pair is subtracted from an integer, the resulting Pair's elements #are the integer minus the first element, and the integer minus the second #element sub subtract { my ($obj, $arg, $swap) = @_; if (ref $arg and $arg->isa(ref ($obj))){ #if second argument is another Pair: bless [$obj->[0] - $arg->[0], $obj->[1] - $arg->[1]], ref $obj; } else { #second argument is an integer (we're assuming) if (!$swap){ #arguments were not swapped. It's Pair - Integer bless [$obj->[0] - $arg, $obj->[1] - $arg], ref $obj; } else { #arguments were swapped. It's Integer - Pair bless [$arg - $obj->[0], $arg - $obj->[1]], ref $obj; } } } 1;