in reply to Parsing parenthetical arguments recursively

And a colleague looking over my shoulder points and says: You have to escape your |'s. And I stare. And I splutter. And I try what he suggests, and it appears to work miraculously well.

If the Great Holy Monks have further input, I am forever grateful.

Revised code:
#! /usr/bin/perl #sample string. $string = "((2 > 1) | ('word' eq 'toy'))"; #next line converts user-specified operators into Perl #logical operators. $string =~ s/([&|]{1})/$1$1/g; print "Initial parsed string = $string\n"; #Look ahead assertion. while ($string =~ /\(((?:[^()])*?)\)/) { my $assert = $1; my $val = (eval $1) ? 1 : 0; print "Case to be evaluated = $1\n"; print "Evaluated value = $val\n"; $assert =~ s/\|\|/\\\|\\\|/g; $string =~ s/\($assert\)/$val/; print "Parsed string = $string\n"; } print "Result: $string\n";

Replies are listed 'Best First'.
Re: Re: Parsing parenthetical arguments recursively
by Anonymous Monk on Aug 15, 2003 at 19:38 UTC
    Its possible you want to quotemeta() $assert instead, but I could see it going either way.
Re: Re: Parsing parenthetical arguments recursively
by waswas-fng (Curate) on Aug 15, 2003 at 22:29 UTC
    So you don't want to test and reject unbalanced parens? for instance:
    $string = "((2 > 1) | ('word' eq 'toy')))";
    If you did you may want to use one of the balanced modules to verify balance of the parens.

    -Waswas
      The same code(now working) is being used to accomplish that, actually. I use the same regexp when the user supplies the expression to verify its validity, without doing any evaluation on it:

      while ($tmp =~ /\(((?:[^()])*?)\)/) { my $assert = $1; $assert =~ s/\|/\\\|/g; $tmp =~ s/\($assert\)/$1/; } ($tmp =~ /\(|\)/) ? print "Don't match.\n" : print "Match.\n";

      Just as a purely hypothetical example. Though, I will definitely look into those modules, as I'd not heard of them before. Thank you for the link.

      ~Moe~