#!/usr/bin/perl -l use strict; use warnings; { package Number; use overload '+' => \&plus, '""' => \&value, fallback => 1; use Scalar::Util qw(blessed looks_like_number); use Carp qw(carp croak); sub new { my ( $class, $number ) = @_; unless ( looks_like_number($number) ) { croak("($number) is not a valid number"); } return bless { number => $number } => $class; } sub value { shift->{number} } sub plus { my ( $num1, $num2, $reversed ) = @_; if ($reversed) { carp("$num1 and $num2 are reversed"); } return __PACKAGE__->new( $num1->value + ( blessed $num2 ? $num2->value : $num2 ) ); } } my $seven = Number->new(7); my $pi = Number->new(3.14); # overloading stringification ('""') allows the following to work print $seven + $pi; # 'blessed' in &plus allows this to work print $seven + $pi + 1 + $pi; # without overloading, the above is: print $seven->plus($pi)->plus(1)->plus($pi)->value; # perl's smart enough to reverse these print 3 + $seven;