package My::SuperNumber;
use overload (
# overload the subtraction operator
'-' => sub {
my($self, $other, $swap) = @_;
my $result = $self->my_super_subtract($other);
return $swap ? -$result : $result;
},
);
####
use overload (
# this is the cryptic name of the "numification" operator
'0+' => sub {
my($self, $other, $swap) = @_;
return $self->as_number;
},
);
####
use overload (
# this is the cryptic name of the "stringification" operator
'""' => op_stringify,
);
# and then in the XS code:
char *
op_stringify(left, right, swap)
SV * left
SV * right
bool swap
CODE:
RETVAL = my_stringify(left);
OUTPUT:
RETVAL
####
sub as_string {
my($obj) = @_;
return "$obj" unless ref $obj;
die "Give me a string, or something that pretends to be one"
unless overload::Method($obj, '""');
return "$obj";
}
####
sub as_string {
my($obj) = @_;
return "$obj" unless ref $obj;
my $method = overload::Method($obj, '""')
or die "Give me a string, or something that pretends to be one";
# WRONG
return $method->($obj);
# RIGHT
return $method->($obj, undef, 0);
}