What is the best practice for finding out all superclasses of a Perl class?

会有一股神秘感。 提交于 2019-12-04 03:05:44

问题


Is there a standard CPAN way of finding out all the superclasses of a Perl class (or better yet entire superclass tree, up to UNIVERSAL)?

Or is the best practice to simply examine @{"${$class}::ISA"} for each class, class's parents etc...?


回答1:


There is no "standard way" because this is not a standard thing you want to do. For anything other than visualization it is an OO red flag to want to inspect your inheritance tree.

In addition to Class::ISA, there is mro::get_linear_isa(). Both have been in core for a while so they could be considered "standard" for some definition. Both of those show inheritance as a flat list, not a tree, which is useful mostly for deep magic.

The perl5i meta object provides both linear_isa(), like mro (it just calls mro), and ISA() which returns the class' @ISA. It can be used to construct a tree using simple recursion without getting into symbol tables.

use perl5i::2;

func print_isa_tree($class, $depth) {
    $depth ||= 0;

    my $indent = "    " x $depth;
    say $indent, $class;

    for my $super_class ($class->mc->ISA) {
        print_isa_tree($super_class, $depth+1);
    }

    return;
}


my $Class = shift;
$Class->require;

print_isa_tree($Class);

__END__
DBIx::Class
    DBIx::Class::Componentised
        Class::C3::Componentised
    DBIx::Class::AccessorGroup
        Class::Accessor::Grouped



回答2:


I think Class::ISA is something like you are looking for

use Class::ISA;
use Mojolicious;
print join "\n", Class::ISA::super_path("Mojolicious");

Prints:

Mojo
Mojo::Base

However, it's not some kind of "best practice" since the whole task isn't something Perl programmers do every day.




回答3:


I don't believe that there is something like a "standard CPAN way". Examining @ISA is common practice - and also plausible, since techniques like use base qw(...) and use parent -norequire, ... also operate on top of @ISA...




回答4:


Most likely these days you want to use one of the functions from mro, such as mro::get_linear_isa.

use mro;
my @superclasses = mro::get_linear_isa($class);


来源:https://stackoverflow.com/questions/10870581/what-is-the-best-practice-for-finding-out-all-superclasses-of-a-perl-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!