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

I am confusing with super keyword.Can you explain me why we used.What is advantage for using Super Keyword in perl OOPS.

Replies are listed 'Best First'.
Re: purpose of Super keyword
by kennethk (Abbot) on Feb 10, 2010 at 21:39 UTC
    First, note that Perl is case-sensitive, and the pseudo-package (not keyword) is SUPER. The short answer is that it allows a derived class to call its parent's version of an overridden method without hard-coding the parent package in the method, i.e.:

    sub get_coordinates { $self = shift; return $self->SUPER::get_coordinates(), get_z(); }

    This is explained in much more detail in the Overridden Methods section of perltoot, which you should read if you want to learn about OO mechanics in Perl.

Re: purpose of Super keyword
by pajout (Curate) on Feb 10, 2010 at 22:20 UTC
    Consider following example:

    test.pl:
    #!/usr/bin/perl use Data::Dumper; use Animal::Dog; my $rex = Animal::Dog->new(); print Dumper($rex);

    Aninal.pm:
    package Animal; use strict; use warnings; sub new { my ($class) = @_; my $proto = {need_oxygen => 1}; return bless($proto, $class); } 1;

    Animal/Dog.pm:
    package Animal::Dog; use base "Animal"; use strict; use warnings; sub new { my ($class) = @_; my $self = $class->SUPER::new(); $$self{domesticated} = 1; return $self; } 1;

    Running test.pl will return:
    $VAR1 = bless( { 'domesticated' => 1, 'need_oxygen' => 1 }, 'Animal::Dog' );

    When parent method (Animal::new in the example) does something important (it sets 'need_oxygen' for all animals), you can call it WITHOUT explicit hardcoding of the parent class, as was already noticed.

    For instance, in Animal::Dog::Husky->some_method body, you can call some inherited method and you do not care if that method is written in Animal or in Animal::Dog class.

    UPDATE: s/inherited/overiden/

Re: purpose of Super keyword
by Anonymous Monk on Feb 10, 2010 at 21:40 UTC