Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass arguments to a Perl 6 grammar?

Tags:

grammar

raku

In Edit distance: Ignore start/end, I offered a Perl 6 solution to a fuzzy fuzzy matching problem. I had a grammar like this (although maybe I've improved it after Edit #3):

grammar NString {
    regex n-chars { [<.ignore>* \w]**4 }
    regex ignore  { \s }
    }

The literal 4 itself was the length of the target string in the example. But the next problem might be some other length. So how can I tell the grammar how long I want that match to be?

like image 589
brian d foy Avatar asked Jul 24 '17 03:07

brian d foy


1 Answers

Although the docs don't show an example or using the $args parameter, I found one in S05-grammar/example.t in roast.

Specify the arguments in :args and give the regex an appropriate signature. Inside the regex, access the arguments in a code block:

grammar NString {
    regex n-chars ($length) { [<.ignore>* \w]**{ $length } }
    regex ignore { \s }
    }

class NString::Actions {
    method n-chars ($/) {
        put "Found $/";
        }
    }

my $string = 'The quick, brown butterfly';

loop {
    state $from = 0;
    my $match = NString.subparse(
        $string,
        :rule('n-chars'),
        :actions(NString::Actions),
        :c($from++),
        :args( \(5) )
        );

    last unless ?$match;
    }

I'm still not sure about the rules for passing the arguments though. This doesn't work:

        :args( 5 )

I get:

Too few positionals passed; expected 2 arguments but got 1

This works:

        :args( 5, )

But that's enough thinking about this for one night.

like image 173
brian d foy Avatar answered Sep 18 '22 14:09

brian d foy