Hello siegried,

This is a fun question! In fact, v5.10 introduced "recursive subpatterns"
into the regex lexicon, so using v5.10 or later, it is possible to
implement (rather arcane) recursive descent regexes without resorting to
eval-based tricks like what you have.

But before diving in, a few questions are in order to make sure we're
working on the right problem. Are you looking for something to cram into a
one-liner? (Do you have a character limit for your one-liner?) Are you open
to solving this with a combination of for-loops and regexes, or do you want
a purely regex-based approach? Are you trying to write something that
merely validates that an expression as valid mathematics, or do you want to
build an abstract syntax tree? Are you interested in using modules from
CPAN or rolling your own? Finally, if your answer to all of these is, "I'm
just curious!", then you can expect to get a very wide range of answers,
not just regex-based.

Thanks! Looking forward to the fun!
David

On Sat, Aug 13, 2016 at 3:45 PM, Richard Heintze via beginners <
beginners@perl.org> wrote:

> I this perl one liner for evaluating infix expressions in VI and emacs/VI
> emulator mode:
>
>
>
> .! perl -MPOSIX   -pe ' BEGIN{ $np = qr{ \( (?: (?> [^()]+ ) | (??{ $np })
> )* \) }x;$funpat = qr/$np/;} s/($funpat)=($funpat|(")[^\"]*
> (")|[0-9\.]+)/"$1=$3".eval($1)."$4"/ge'
>
> That $np is from the camel book and it is a regular expression that parses
> nested sets of parentheses and then my replace command evaluates the
> arithmetic expression.
>
> Since perl accommodates recursive regular expressions, it ought to be
> possible to implement a recursive decent parser.
>
> Can someone help me enhance the above code so that instead of just blindly
> looking for balanced parenthesis, the regular expression will recognize
> (match) this:
>
> 5+8*(2+8/(3+2))*(2+22/3)=()
> Thanks
> siegfried
>
>
>


-- 
 "Debugging is twice as hard as writing the code in the first place.
  Therefore, if you write the code as cleverly as possible, you are,
  by definition, not smart enough to debug it." -- Brian Kernighan

Reply via email to