use 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]); } | 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);