How to make Perl 6 grammar more than one (for example: ex and: ov)?

I want grammarto do something like this:

> "abc" ~~ m:ex/^ (\w ** 1..2) (\w ** 1..2) $ {say $0, $1}/
「ab」「c」
「a」「bc」

Or like this:

> my regex left { \S ** 1..2  }
> my regex right { \S ** 1..2  }
> "abc" ~~ m:ex/^ <left><right> $ {say $<left>, $<right>}/
「ab」「c」
「a」「bc」

Here is mine grammar:

grammar LR {
  regex TOP {
    <left> 
    <right>
  }
  regex left {
    \w ** 1..2 
  }
  regex right {
    \w ** 1..2 
  }
}

my $string = "abc";
my $match = LR.parse($string);
say "input: $string";
printf "split: %s|%s\n", ~$match<left>, ~$match<right>;

His conclusion:

$ input: abc
$ split: ab|c

So, it <left>can only be greedy without leaving anything <right>. How do I change the code to fit both of the options?

$ input: abc
$ split: a|bc, ab|c
+4
source share
2 answers

Grammars are designed to provide zero or one answer, nothing more, so you need to use some tricks to get them to do what you want.

Since it Grammar.parsereturns only one object Match, you should use a different approach to get all matches:

sub callback($match) {
    say $match;
}
grammar LR {
    regex TOP {
        <left> 
        <right>
        $
        { callback($/) }
        # make the match fail, thus forcing backtracking:
        <!>
    }
    regex left {
        \w ** 1..2 
    }
    regex right {
        \w ** 1..2 
    }
}

LR.parse('abc');

, <!> ( ) , , . , , .

, LR.parse, , ; .

API ( ) gather/take :

grammar LR {
    regex TOP {
        <left> 
        <right>
        $
        { take $/ }
        # make the match fail, thus forcing backtracking:
        <!>
    }
    regex left {
        \w ** 1..2 
    }
    regex right {
        \w ** 1..2 
    }
}

.say for gather LR.parse('abc');
+4

, , , " Perl 6 Regexes and Grammars" , , . , , ...

, - grammar.parse , :exhaustive , , @evb, /, (S05) # perl6 # perl6-dev irc.

7 S05:

[regex], , [eg :exhaustive], , (, m// [ grammar.parse]), rx// [ regex { ... }].

( [eg :exhaustive], [ grammar.parse] [ regex { ... }]] - //, SO. .)

5 :exhaustive ( ). 2 jnthn , , , . 30 . 7 .

1 # perl6 ( emphasis, ): "regexes " .

Hth.

+3

Source: https://habr.com/ru/post/1688035/


All Articles