(Unknown Poster) wrote:
: X-No-archive: yes
Why? Yours is a good question.
: package Rational;
:
: use overload "0+" => \&float;
:
: # There is a subroutine called float() that, well, returns a float.
: ------
: use Rational;
: #$fraction holds an object of type Rational
: my $fsq = sqrt($fraction);
: ------------
: perl complains:
: Operation sqrt: no method found, argument in overloaded package Rational at ...
:
: Since sqrt() takes a numeric argument, I expected the overloading of "0+"
: to force float() to be called on the object $fraction, but it doesn't work.
Because sqrt() is itself an overloadable operator.
You can either let the overload pragma handle this on its own:
use overload
"0+" => \&float,
fallback => 1;
or, probably better, go ahead and overload sqrt:
use overload
"0+" => \&float,
"sqrt" => sub { sqrt($_[0]->float) };