in reply to Parse:RecDescent grammar help


lolo,

I've been just learning Parse::RecDescent myself so this was a good exercise for me.... This should do the trick
- You can define plain variables, arrays or hashes
- takes semi-colons at the end (just to be pretty)
- the two options on hashelement and array term are for with and without commas (maily for the last element of the array not 'requiring' a comma after it...

Most of the rest should be pretty self explanitory, you might want to add another type inside 'term' so you can make a varible on of the options i.e. $var = $var2 or the like
=) (my first answered question...woot!)


regards Paul
#!/usr/bin/perl use strict; use warnings; use Data::Dumper (); use Parse::RecDescent (); use strict; use warnings; my $grammar = q{ # --- Tokens --- EOF : /^\Z/ IDENTIFIER : /[A-Za-z]\w*/ LITERAL : /\d+/ VAR : '$' ARRAY : '@' HASH : '%' EQUAL : '=' QUOTE : '"' HASHASSIGN : '=>' # --- Rules --- parse : stmt(s?) EOF { $item[1] } stmt : variable ';' { $item[1] } | array ';' { $item[1] } | hash ';' { $item[1] } | <error> arrayterm : term ',' { [ @item[0, 1] ] } | term { [ @item[0, 1] ] } array : ARRAY IDENTIFIER EQUAL arrayterm(s?) { [ $item[2, 4] ] } hashelement : IDENTIFIER HASHASSIGN term ',' { [ @item[0,1] ] } | IDENTIFIER HASHASSIGN term { [ @item[0,1] ] } hash : HASH IDENTIFIER EQUAL '{' hashelement(s?) '}' { [ @item [0, 2, 5] ] } variable : VAR IDENTIFIER EQUAL term { [ @item[0, 2, 4] ] } term : QUOTE IDENTIFIER QUOTE { [ 'identifier', $item[2 +] ] } | LITERAL { [ 'literal', $item[1] ] } }; $::RD_HINT = 1; my $parser = Parse::RecDescent->new($grammar); die("Bad grammar.\n") unless defined($parser); my $text = q { $dog = 5; $dog = "fluffy"; @arr = 5,"canary",7; %stuff = { animal => "dog", age => 5, name => "fluffy" }; }; my $result = $parser->parse(\$text); die("Bad text.\n") unless (defined($result)); print Data::Dumper::Dumper($result);