This will produce a spiffy data structure for you. I'm assuming that you can get the array into is_valid_color cleanly.
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]); } | <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);
output is
$VAR1 = [ { 'color' => 'red', 'item' => 'pencil', 'quant' => '1' }, { 'color' => 'blue', 'item' => 'pencil', 'quant' => '2' }, { 'color' => 'green', 'item' => 'pen', 'quant' => '4' } ];
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.

In reply to Re: Dynamic expansion of tokens with Parse::RecDescent by amw1
in thread Dynamic expansion of tokens with Parse::RecDescent by jaldhar

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.