So inspired by both this post by moritz and the awesome Regexp::Grammars module on CPAN, I created a Perl 5.10 version of the perl 6 code (also using GraphViz::Data::Grapher). There are a few differences, such as naming the top rule, the '' element that Regexp::Grammars creates, and the output format which comes from GraphViz::Data::Grapher (I am outputting to png since GraphViz's as_svg [well dot's SVG output, technically] outputs the wrong size for the outer svg tag).
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
use Regexp::Grammars;
use Data::Dumper;
use GraphViz;
use GraphViz::Data::Grapher;
my %fruit = map { $_ => '' } qw(apple banana);
my %currency = map { $_ => '' } qw($ USD dollar EUR € );
my $x = 'just 20,000 dollar per apple';
my $parser = qr{
<price_description>
<rule: price_description>
<value> <currency> per <fruit>
<rule: currency> <%currency>
<rule: fruit> <%fruit>
<rule: value> <[number]> ** ( , )
<rule: number> \d+
}msx;
$x =~ $parser;
my $g = GraphViz::Data::Grapher->new(\%/);
print $g->as_png;
Leave a comment