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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.