7

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?

brian d foy
  • 129,424
  • 31
  • 207
  • 592

1 Answers1

5

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.

brian d foy
  • 129,424
  • 31
  • 207
  • 592
  • 2
    It's expecting to be passed a `Capture`, and if it doesn't get one then calls the `.Capture` coercer. A `List` will coerce to a `Capture` with the list elements as the positional arguments. An `Int` doesn't turn into anything useful (it falls back to the `Mu.Capture`, which takes public attributes and uses those as named parameters; an `Int` has no public attributes). – Jonathan Worthington Jul 24 '17 at 08:18
  • How do any of those turn into two arguments? – brian d foy Jul 24 '17 at 13:11
  • i expect that refers to the invocant, i.e. the "self" argument, as regexes in a class are methods. – timotimo Jul 24 '17 at 22:53