It's basically the same problem as recursive algorithm for nested data structures

Update: Actually, it's a bit more different than I thought because you said you can't have both OR and AND in the same list.

# make_parser.pl use strict; use warnings; use Parse::RecDescent qw( ); my $grammar = <<'__EOI__'; { use strict; use warnings; sub dequote { my ($s) = @_; $s =~ s/^"//; $s =~ s/"\z//; $s =~ s/\\(.)/$1/sg; return $s; } } parse : list /\Z/ { $item[1] } list : term list_[ $item[1] ] list_ : "AND" <commit> and_list { [ $item[1] => $arg[0], @{$item[3]} ] } | "OR" <commit> or_list { [ $item[1] => $arg[0], @{$item[3]} ] } | { $arg[0] } and_list : term and_list_ { [ $item[1], @{$item[2]} ] } and_list_ : "AND" <commit> term and_list_ { [ $item[3], @{$item[4]} ] } | { [] } or_list : term or_list_ { [ $item[1], @{$item[2]} ] } or_list_ : "OR" <commit> term or_list_ { [ $item[3], @{$item[4]} ] } | { [] } term : IDENT | STRING | '(' list ')' { $item[2] } IDENT : /\w+/ STRING : /"(?:\\.|[^\\])*"/s { dequote($item[1]) } __EOI__ Parse::RecDescent->Precompile($grammar, 'Parser') or die("Bad grammar\n");
# test.pl use strict; use warnings; use Data::Dumper qw( Dumper ); use Parser qw( ); my $text = 'dogs OR cats OR "flying fish" OR (shrimp AND squid)'; my $parser = Parser->new(); print(Dumper($parser->parse($text)));
>perl make_parser.pl >perl test.pl $VAR1 = [ 'OR', 'dogs', 'cats', 'flying fish', [ 'AND', 'shrimp', 'squid' ] ];

Update: Small changes to grammar to eliminate backtracking.


In reply to Re: Break string into array by ikegami
in thread Break string into array by Anonymous Monk

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.