Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a list of classes derived from given base class in Perl

Tags:

oop

perl

Given a base class and a list of classes derived from it:

package base
{
    # ...
}

package foo
{
    our @ISA = 'base';
    # ...
}

package bar
{
    our @ISA = 'base';
    # ...
}

Is there a runtime way to get a list of classes which have base as parent?

I know I could easily work around this by adding their names to a list manually, but I was wondering if base itself could tell me who inherited from it.

like image 752
DevSolar Avatar asked Oct 18 '25 12:10

DevSolar


1 Answers

Since Perl 5.10, Perl has come with a module called mro which includes a whole bunch of functions for inspecting class hierarchies.

You can find child classes of My::Class using:

use mro;

my $base_class = 'My::Class';
print "$_\n" for @{ mro::get_isarev( $base_class ) };

The mro documentation includes various caveats, such as the fact that calling it on the 'UNIVERSAL' package doesn't work properly. There will be other cases it copes badly with, but if you're "doing normal stuff", it should work.

like image 81
tobyink Avatar answered Oct 21 '25 01:10

tobyink