http://www.perlmonks.org?node_id=522505


in reply to Parse::RecDescent and Dynamically Matched Subrule Repetition

This is the best I could come up with.. It's possible that this could be improved, as it's a little messy. Anyway, in P::RD you can pass arguments to a subrule using rule[args], and within the rule use the @arg or %arg variable to fetch those args.
#!/usr/bin/perl use strict; use warnings; use Test::More tests => 6; use Parse::RecDescent; my $p = Parse::RecDescent->new(<<'END_GRAMMAR') or die; rec: int elem[ num => $item[1] ] /\Z/ { $item[2] } int: /\d+\b/ ## match either the elem_many or the elem_one rule, and pass ## the number along to it.. elem: { $arg{num} > 1 ? "many" : "one" } <matchrule:elem_$item[1]>[ num => $arg{num} ] { $item[2] } elem_many: elem_one elem[ num => $arg{num}-1 ] { [ $item[1], @{$item[2]} ] } elem_one: /\S+(?!\S)/ { [$item[1]] } END_GRAMMAR # ok( $p->rec('0')); ok( $p->rec('1 foo')); ok( $p->rec('2 foo bar')); ok(!$p->rec('1')); ok(!$p->rec('1 foo bar')); ok( $p->rec('3 foo bar baz')); ok(!$p->rec('3 foo bar baz flab'));
It works for everything except the zero case, which shouldn't be too bad to add as a degenerate case.

Also note that I added a /\Z/ token to the main rule, so we would be assured that the rule was matching the whole string. And I also changed /\S+/ to /\S+(?!\S)/ to make sure each elem was a maximum-length word.

BTW, you could do this simple problem with extended regexes: something like /(\d+)\s+(??{ "(?:\\S+(?>\\S)\\s*){$1}" })/ off the top of my head. But if elem_one were matching anything significantly more complicated /\S+/, you'd have to do something like this in a grammar.

blokhead