Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to become comfortable in Perl 6. One of the things I found handy in Python when I was at a REPL prompt was that I could do a dir(object) and find out the attributes of an object, which in Python includes the object's methods.

This often served as a helpful reminder of what I wanted to do; 'Oh, that's right, trim in Python is called strip', that sort of thing.

In Perl 6, I know about the introspection methods .WHO, .WHAT, .WHICH, .HOW and .WHY, but these are at a class or object level. How do I find out what's inside an object, and what I can do to it?

like image 286
Steve Piner Avatar asked Apr 01 '16 23:04

Steve Piner


1 Answers

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

You mentioned that you already know about the introspection methods - but are you aware of what you can find out by querying an objects metaobject (available from .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'
>

There is a shortcut for querying an object's metaobject; a.^b translates to a.HOW.b(a). The methods and attributes for Article are themselves objects - instances of Method and Attribute. Whenever you call .say on an object, you implicitly call its .gist method which is meant to give you a summarized string representation of the object - i.e. the 'gist' of it.

The attributes of the builtin Str type appear to be of type BOOTSTRAPATTR type - which doesn't implement the .gist method. As an alternative, we can just ask for the attributes to spit out their names instead;

> 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)
>

You can find our more here (which is where just about everything for this answer came from).

like image 122
Marty Avatar answered Oct 02 '22 09:10

Marty