Determine if base class subroutine has been overridden from the base class

Viewed 224

This question had stumped me but I have since solved the problem and will post my answer.

I have a base class called Parent

Parent

package Parent;

sub new {
    my $c = shift;
    my $s = {}, bless $s, $c;
    return $s;
}

sub who {
    return "parent";
}

1;

This parent class exposes a single method; who.

I wrote two child classes: Child and Freak. Only Child overrides who.

Child

package Child;

use base 'Parent';

sub who {
    return "child";
}

1;

Freak

package Freak;

use base 'Parent';

1;

How can the base class determine whether the base who method has been overridden?

I want to be able to write something like this

package Parent;

sub new {
    my $c = shift;
    my $s = {}, bless $s, $c;
    return $s;
}

sub who {
    return "parent";
}

sub check {
  my $self = shift;

  my $is_overridden = 1; # what conditional should be here?

  return $is_overridden ? "yes" : "no";
}

1;

What conditional can I use to determine if the subroutine is overridden?

3 Answers
Related