package Example::Tuple;
use overload(
'""' => \&asString,
);
sub new
{
my( $class, @coords )= @_;
return bless \@coords, $class;
}
sub asString
{
my( $self )= @_;
return "(" . join(",",@$self) . ")";
}
####
require Example::Tuple;
my $origin= Example::Tuple->new( -3, 5 );
my $dest= Example::Tuple->new( 2, 1 );
print "Now draw a line from $origin to $dest.\n";
####
Now draw a line from (-3,5) to (2,1).
####
package Example::Tuple;
use overload(
'eq' => \&isEqual,
);
# ...
sub isEqual
{
my( $self, $arg, $isReversed )= @_;
# We ignore $isReversed since ($x eq $y) is also ($y eq $x)
return 0 # Tuples of different sizes are never equal
if @$self != @$arg;
for my $i ( 0 .. $#$self ) {
return 0 # Tuples differ if any paired elements differ
if $self->[$i] ne $arg->[$i];
}
return 1; # Otherwise they are equal.
}
####
require Example::Tuple;
my $w= Example::Tuple->new( 3, 4 );
my $x= Example::Tuple->new( 4, 3 );
my $y= Example::Tuple->new( 3, 4 );
my $z= $w;
print "w and z are the same object.\n"
if $w == $z;
print "$w and $y are at the same position.\n"
if $w eq $y;
print "$x and $y are at different positions.\n"
unless $x eq $y;
####
package Example::Tuple;
use overload(
'.' => \&concatString,
);
sub concatString
{
my( $self, $string, $isReversed )= @_;
my @new;
for my $elt ( @$self ) {
push @new, $isReversed
? $string . $elt
: $elt . $string;
}
return __PACKAGE__->new( @new );
}