I am new to RecDescent and need a little guidance. I am parsing a custom file format to convert it to XML. I have the token parsing down, but I am having trouble building the XML tree as the tokens are evaluated inside-out versus outside-in (hope that makes sense). I'm sure autotree might be able to help me, but wasn't able to get it working only referring to the man page. Any assistance would be greatly appreciated!
---------------
Input File
---------------
CAR(agg)=(
ID(str)='12345'
TITLE(agg)=(
TITLE(text 5)='Prius'
)
RATING(text 4)='Good'
CAT(agg)=(
LABEL(text 6)='Hybrid'
REL(int)=8
)
CAT(agg)=(
LABEL(text 6)='Family'
REL(int)=10
)
)
CAR(agg)=(
ID(str)='22222'
TITLE(agg)=(
TITLE(text 7)='Voyager'
)
RATING(text 3)='Bad'
CAT(agg)=(
LABEL(text 6)='Family'
REL(int)=10
)
CAT(agg)=(
LABEL(text 3)='Van'
REL(int)=9
)
)
---------------
Perl Script
---------------
#!/usr/bin/perl
use Parse::RecDescent;
$grammar = q{
startrule: root(s)
root: object {
print "root\n";
}
object: name "(agg)=(" body(s?) closeobject {
print "object <$item{name}>\n";
}
name: /\w+/
body: /\s+/
| object
| property { print "property $item{property}\n"; }
property: name /\(\w+\s*\d*\)=/ value {
"<$item{name}>$item{value}</$item{name}>" }
value: value1 | value2
value1: /\w+/
value2: /'.+'/ { substr $item[1], 1, (length $item[1]) - 2 }
closeobject: ")" {
print "close\n";
}
};
$parser = Parse::RecDescent->new($grammar);
undef $/;
$text = <>;
print "<ROOT>\n";
$parser->startrule($text);
print "</ROOT>\n";
---------------
Desired Output
---------------
<ROOT>
<CAR>
<ID>12345</ID>
<TITLE>Prius</TITLE>
<RATING>Good</RATING>
<CAT>
<LABEL>Hybrid</LABEL>
<REL>8</REL>
</CAT>
<CAT>
<LABEL>Family</LABEL>
<REL>10</REL>
</CAT>
</CAR>
<CAR>
<ID>22222</ID>
<TITLE>Voyager</TITLE>
<RATING>Bad</RATING>
<CAT>
<LABEL>Family</LABEL>
<REL>10</REL>
</CAT>
<CAT>
<LABEL>Van</LABEL>
<REL>9</REL>
</CAT>
</CAR>
</ROOT>
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.