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

Hi, How can we implement polymorphism in object oriented perl?

Replies are listed 'Best First'.
Re: How to use polymorphism in perl
by tobyink (Canon) on Sep 30, 2012 at 08:12 UTC
    use 5.014; package Car { sub new { bless \@_, shift } sub go { say "brmm!" } } package Spacecraft { sub new { bless \@_, shift } sub go { say "whoosh!" } } my $vehicle = int(rand 2) ? Car->new : Spacecraft->new; # Is $vehicle a car or a spacecraft? # It doesn't matter! $vehicle->go;
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: How to use polymorphism in perl
by Athanasius (Archbishop) on Sep 30, 2012 at 09:08 UTC

    Hello ramu, and welcome to the Monastery!

    Perl provides two three mechanisms to facilitate OO polymorphism: inheritance, method overloading as illustrated by tobyink above, and operator overloading, via the overload pragma detailed in the perldoc article overload.

    A useful example of operator overloading in action is provided by the standard module Math::Complex. The documentation for this module notes that:

    Thanks to overloading, the handling of arithmetics with complex numbers is simple and almost transparent.

    For example, when complex numbers created using this module are added using the + operator, operator overloading ensures that Perl performs an addition operation suitable for complex numbers. But when ordinary floating-point numbers are added, Perl applies the standard (non-overloaded) addition operation. In other words, the same syntax is used for adding different types of numbers, but the additions actually performed are tailored to the particular types of the numbers being added — which is the essence of polymorphism.

    Hope that helps,

    Update: Amended to take account of the post by Anonymous Monk, below. Apparently, I’m still thinking C++ instead of Perl.  :-(

    Athanasius <°(((><contra mundum

      Well, tobyink doesn't really demonstrate inheritance, as long the class defines the method , you can call it on an object
Re: How to use polymorphism in perl
by Anonymous Monk on Sep 30, 2012 at 08:01 UTC