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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With