How can I pass arguments to a Perl 6 grammar?

扶醉桌前 提交于 2020-01-03 10:26:39

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/45272238/how-can-i-pass-arguments-to-a-perl-6-grammar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!