Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl 6, is there a way to get the Pod declarator block that is attached to a specific multi sub candidate?

Perl 6 has a cool feature which allows one to get any Pod declarator block that is attached to a subroutine (or class, role, etc.), using the WHY method:

#|(Some enlightening words about myfunc.)
sub myfunc (Int $i) { say "You provided an integer: $i"; };
#=(Some more words about myfunc.)

say &myfunc.WHY;

This displays:

Some enlightening words about myfunc.
Some more words about myfunc.

Unfortunately, when one has multiple candidates for a subroutine, one can't just invoke .WHY on the subroutine name:

#|(myfunc accepts an integer.)
multi myfunc (Int $i) { say "You provided an integer $i"; };
#|(myfunc accepts a string.)
multi myfunc (Str $s) { say "You provided a string $s"; };

say &myfunc.WHY;

The result:

No documentation available for type 'Sub'.
Perhaps it can be found at https://docs.perl6.org/type/Sub

Is there a way to get the Pod declarator block that is attached to a specific multi sub candidate? Is there a way to do so for all a subroutine's candidates?

like image 242
Enheh Avatar asked Apr 09 '18 13:04

Enheh


1 Answers

You look up the multi with candidates or cando.

When initially posted I couldn't find a canned method for looking up a multi sub by signature but Christoph remedied that.

#| Initiate a specified spell normally
multi sub cast(Str $spell) {
  say "casting spell $spell";
}
#= (do not use for class 7 spells)

#| Cast a heavy rock etc in irritation
multi sub cast(Str $heavy-item, Int $n) {
  say "chucking $n heavy $heavy-item";
}

say "doc for cast spell";
say &cast.candidates[0].WHY;

say "doc for throwing rocks";
say &cast.candidates[1].WHY;

say "find doc for throwing things";
for &cast.candidates {
    if .signature ~~ :( Str, Int ) {
        say .WHY;
    }
}

# more advanced
say &cast.cando(\(Str, Int))>>.WHY; # thanks to Christoph
&cast.candidates.first: { .signature ~~ :(Str, Int) } andthen .WHY.say;

OUTPUT:

doc for cast spell
Initiate a specified spell normally
(do not use for class 7 spells)
doc for throwing rocks
Cast a heavy rock etc in irritation
find doc for throwing things
Cast a heavy rock etc in irritation
... repeated for variants ...
like image 69
mr_ron Avatar answered Jan 04 '23 11:01

mr_ron