Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

How to implement Overloading/Polymorphism concept in perl

Replies are listed 'Best First'.
Re: Polymorphism in Perl
by moritz (Cardinal) on Feb 07, 2011 at 09:24 UTC

      You don't need inheritance (much less method overriding) for polymorphism in Perl. You can just use duck typing, where you design an interface that consists of one or more method calls and then any object or class that implements that interface can be passed to code that makes use of that interface.

      Note that Perl itself doesn't provide a way to declare "interfaces" so when I say "design an interface", I'm talking about documentation for humans not coding. Though, languages like C++ and Java that support declaring an interface don't actually express interfaces fully, of course, so designing an interface there should also involve documentation for humans, not just writing a bunch of method signatures.

      - tye        

        sub feedDucks { while (my $object = shift) { if ( $object->can('walk') and $object->can('quack') and $object->can('swim') and $object->can('feed') ) { $object->feed('breadcrumbs'); }else{ warn "Insufficient mana to polymorph $object!"; } } }
Re: Polymorphism in Perl
by doug (Pilgrim) on Feb 07, 2011 at 16:19 UTC

    Another thing to consider are "roles" as provided by Moose.