Constructing a string by printing things during the parsing phase is a really bad idea. Things don't necessarily happen in an intuitive order, and some productions may be applied but then rolled back based on the rest of the parse (especially in recursive descent parsing). Use the productions for what they were intended -- returning a semantic value. In this case, the productions should return the appropriate parts of the XML representation.
my $p = Parse::RecDescent->new( <<'END_GRAMMAR' ); parse: item(s) { "<ROOT>" . join("", @{$item[1]}) . "</R +OOT>" } item: /\w+/ /\([^\)]+\)=/ data { "<$item[1]>$item[3]</$item[1]>" } data: aggregate | string | integer aggregate: "(" item(s) ")" { join "", @{$item[2]} } string: /'([^']*)'/ { $1 } integer: /\d+/ { $item[1] } END_GRAMMAR undef $/; print $p->parse(<DATA>);
This ignores and does not enforce the "data types" (agg, text N, int) in your markup language. But that would be easy to fix by changing the productions to:
item: /\w+/ "(agg)=" aggregate | /\w+/ "(text" /\d+/ ")=" string | /\w+/ "(int)=" int
(and of course updating the semantic actions accordingly)

Another thing to note is that in your input, there are two layers of "TITLE" tags, but your desired output has only one. You'd have to add a special-case productions to give your desired output (or post-process the XML output):

blokhead


In reply to Re: RecDescent help needed! by blokhead
in thread RecDescent help needed! by pklv

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.