I've never really done any operator overloading in perl, so I was very interesting when I saw this article on perl.com that uses Number::Fraction as an example. But as interesting as the info on overloading was, I couldn't help but get hung up on a particluar line of (non operator related) code ...
sub add { my ($l, $r, $rev) = @_; if (ref $r) { if (UNIVERSAL::isa($r, ref $l)) { return (ref $l)->new($l->{num} * $r->{den} + $r->{num} * $l->{de +n}, $r->{den} * $l->{den}); } else { ...
The key thing that jumps out at me here (unless I'm really missing something about how UNIVERSAL::isa works) is that even though this code will allow the 'add' method to keep working if $l is a Number::Fraction, and $r is a subclass of N::F, or if $l is a subclass of N::F, and $r is a subclass of the subclass, it should still work -- but what if $r and $l are instances of seperate subclasses of N::F ?
Okay, so maybe I'm babling. Consider this (contrived) hierarcy...
Number::Fraction
/ \
Number::MixedFraction Number::Fraction::Tk
Assuming Number::MixedFraction, and Number::Fraction::Tk are both happy to inherit the 'add' method from Number::Fraction (and get a Number::Fraction as the result) then wouldn't it make sense for Number::Fraction::add to be general enough to work in that scenerio?
Isn't this a case where hardcoding 'Number::Fraction' in the class makes sense? ...
sub add { my ($l, $r, $rev) = @_; if (ref $r) { if (UNIVERSAL::isa($r, 'Number::Fraction')) { return (ref $l)->new($l->{num} * $r->{den} + $r->{num} * $l->{de +n}, $r->{den} * $l->{den}); } else { ...
?
In reply to if (UNIVERSAL::isa($r, ref $l)) by hossman
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |