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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|