7

在 Perl5 和 Moose 中,线性 isa线性化 isa有助于理解类层次结构。

方法WHAT显示了值的具体类型:

> 42.WHAT
(Int)

我如何显示类似的东西

> 42.hypothetical-type-hierarchy
(Int) ┬ is (Cool) ─ is (Any) ─ is (Mu)
      └ does (Real) ─ does (Numeric)

… 可能为每个消费角色添加更多台词?


编辑:具有两个角色的示例

class Beta {}
role Delta {}
role Gamma does Delta {}
role Eta {}
role Zeta does Eta {}
role Epsilon does Zeta {}
class Alpha is Beta does Gamma does Epsilon {}

# (Alpha) ┬ is (Beta)
#         ├ does (Gamma) ─ does (Delta)
#         └ does (Epsilon) ─ does (Zeta) ─ does (Eta)

my $ai = Alpha.new
$ai.^mro        # ((Alpha) (Beta) (Any) (Mu))

$ai.^roles      # ((Epsilon) (Zeta) (Eta) (Gamma) (Delta))
                # flat list, not two-element list of a tuple and triple‽
4

1 回答 1

8

您可以使用查询元对象

> 42.^mro
((Int) (Cool) (Any) (Mu))

其中mro代表方法解析顺序

> 42.^roles
((Real) (Numeric))

您可以控制通过副词返回哪些角色(不包括:local从父类继承的角色 - 仅在类上可用)和:!transitive(不包括通过另一个角色组成的角色 - 在角色和类上都可用)。


以下内容应该可以帮助您入门:

my $depth = 0;
for Alpha.^mro {
    say "is {.^name}";
    (sub {
        ++$depth;
        for @_ {
            say '  ' x $depth ~ "does {.^name}";
            &?ROUTINE(.^roles(:!transitive)); # recursive call of anon sub
        }
        --$depth;
    })(.^roles(:local, :!transitive));
}

给定您的示例代码,稍作修改

role Delta {}
role Gamma does Delta {}
role Eta {}
role Zeta does Eta {}
role Epsilon does Zeta {}
class Beta does Gamma {}
class Alpha is Beta does Gamma does Epsilon {}

它产生输出

is Alpha
  does Epsilon
    does Zeta
      does Eta
  does Gamma
    does Delta
is Beta
  does Gamma
    does Delta
is Any
is Mu
于 2017-05-30T07:19:18.083 回答