Perl 6 是否有等同于 Python 的 dir()?

Does Perl 6 have an equivalent to Python's dir()?

我正在努力适应 Perl 6。当我在 REPL 提示符下时,我在 Python 中发现的其中一件事是我可以执行 dir(object) 并找出对象的属性,在 Python 中包括对象的方法。

这通常会提醒我我想做什么; ‘哦,对了,Python里的trim叫strip之类的。

在 Perl 6 中,我知道内省方法 .WHO、.WHAT、.WHICH、.HOW 和 .WHY,但这些是 class 或对象级别的。我如何找出对象内部的内容,以及我可以对它做什么?

How do I find out what's inside an object, and what I can do to it?

您提到您已经了解内省方法 - 但您知道可以通过查询对象元对象(可从 .HOW 获得)找​​到什么吗?

$ perl6
>
> class Article {
*   has Str $.title;
*   has Str $.content;
*   has Int $.view-count;
* }
>
> my Str $greeting = "Hello World"
Hello World
>
> say Article.^methods
(title content view-count)
>
> say Article.^attributes
(Str $!title Str $!content Int $!view-count)
>
> say $greeting.^methods
(BUILD Int Num chomp chop pred succ simplematch match ords samecase samemark 
samespace word-by-word trim-leading trim-trailing trim encode NFC NFD NFKC NFKD 
wordcase trans indent codes chars uc lc tc fc tclc flip ord WHY WHICH Bool Str 
Stringy DUMP ACCEPTS Numeric gist perl comb subst-mutate subst lines split words)
>
> say $greeting.^attributes
Method 'gist' not found for invocant of class 'BOOTSTRAPATTR'
>

查询对象的元对象有快捷方式; a.^b translates to a.HOW.b(a)。 Article 的方法和属性本身就是对象 - MethodAttribute 的实例。每当您在对象上调用 .say 时,您都会隐式调用其 .gist 方法,该方法旨在为您提供对象的摘要字符串表示形式 - 即它的 'gist'。

内置 Str 类型的属性似乎属于 BOOTSTRAPATTR 类型 - 它没有实现 .gist 方法。作为替代方案,我们可以只要求属性吐出它们的名字;

> say sort $greeting.^methods.map: *.name ;
(ACCEPTS BUILD Bool DUMP Int NFC NFD NFKC NFKD Num Numeric Str Stringy WHICH WHY 
chars chomp chop codes comb encode fc flip gist indent lc lines match ord ords perl
pred samecase samemark samespace simplematch split subst subst-mutate succ tc tclc
trans trim trim-leading trim-trailing uc word-by-word wordcase words)
>
> say sort $greeting.^attributes.map: *.name
($!value)
>

您可以找到我们的更多 here(这是此答案的几乎所有内容的来源)。