如何显示值的类型层次结构?

How do you show the type hierarchy of a value?

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

方法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‽

您可以使用

查询元对象
> 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