output isuse Parse::RecDescent; use strict; use Data::Dumper; sub is_valid_color { my $color_to_test = shift(); return $color_to_test if ($color_to_test =~ /red|green|blue/); return undef; } my $grammar = << 'GRAMMAR'; start : order(s) order: quantity color product { $return = { quant => $item{'quantity'}, color => $item{'color'}, item => $item{'product'}, }; } quantity: /\d+/ color: /\w+/ { $return = main::is_valid_color($item[1]); } | <error> product: 'pencil' | 'pen' GRAMMAR my $text; $text = "1 red pencil\n"; $text .= "2 blue pencil\n"; $text .= "4 green pen\n"; my $parser = new Parse::RecDescent($grammar) || die "Bad Grammar"; my $product_list = $parser->start($text) || die "Bad Syntax"; print Dumper($product_list);
I changed item to product to avoid confusion with the multiple contexts of item. Also, you must put pencil before pen as Recdescent will find the first match not the longest match. /pen/ will match both pen and pencil so put pencil first.$VAR1 = [ { 'color' => 'red', 'item' => 'pencil', 'quant' => '1' }, { 'color' => 'blue', 'item' => 'pencil', 'quant' => '2' }, { 'color' => 'green', 'item' => 'pen', 'quant' => '4' } ];
In reply to Re: Dynamic expansion of tokens with Parse::RecDescent
by amw1
in thread Dynamic expansion of tokens with Parse::RecDescent
by jaldhar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |