A while back, I wanted to be able to evaluate expressions from user supplied data without using eval or ///e.

((4+2) * (8 /2)), 5+1, etc...

I started and found it difficult to parse the constructs. Not being one to let things go, I decided to give it another try, mostly as an excercise in hubris.

Currently you can set vars and precedence in the absence of (parens) is left to right but I still found it an interesting challenge.

The reason for the post is that to me it is a challenging problem and I'd like to see what others see wrong with my solution and any ideas on alternative implementation ideas. I'm sure there are bugs and possibly some kruft in here
#!/usr/bin/perl use warnings; use strict; # Operators currently supported. my %Operators = ( '+' => sub { @_ = getsymbolval(@_); my $n=0; $n+=$_ foreach @_; $n + }, '-' => sub { @_ = getsymbolval(@_); my $n=shift; $n-=$_ foreach @_ +; $n }, '*' => sub { @_ = getsymbolval(@_); my $n= shift; $n*=$_ foreach @ +_; $n }, '/' => sub { @_ = getsymbolval(@_); my $n=shift; $n/=$_ foreach @_ +; $n }, '^' => sub { @_ = getsymbolval(@_); my $n=shift; $n = $n ** shift; + $n; }, '=' => sub { no strict; my ($n,$v)=@_; ${'Expression::Evaluate::' +.$n} = getsymbolval($v)}, ); # Symbols are set with symname = val (where symname is [^\w+$]) # Ops supported: + - * / ^(pow) =(assign) { print "Enter an expession..\n"; my $exp = <STDIN>; chomp($exp); last if $exp=~/^quit$/; my $result = parse_expression($exp) ; $result = '' unless $result; # Silence warning for undefined. print "Result: $result\n"; redo; } # Subs ######################################## sub parse_expression { my $exp = shift; my @tokens = (); # Pad out ops with spaces. $exp=~s/(\s*[\(\)\-\>\<=\+\*\/\^])\s*/ $1 /g; # Get tokens push @tokens, $1 while $exp=~/\G\s*"(.*?)"/gc or $exp=~/\G\s*'(.*? +)'/gc or $exp=~/\G\s*(\S+)/gc; if (@tokens == 1 && $tokens[0]=~/^\w+$/){ no strict; return getsymbolval($tokens[0]); } # Find any parens. my (@lp,@rp) = (); for (my $p =0; $p < @tokens; $p++){ if ($tokens[$p] eq '('){ push @lp,$p; }elsif($tokens[$p] eq ')'){ push @rp,$p; } } if ( @lp != @rp){ warn "Mismatched parens in expression."; return; } my @temp = @tokens; for (my $i=0; $i < @rp; $i++){ # Find the match in @lp that is < than. my @wanted; for (my $j = $#lp; $j >= 0 ; $j--){ if ( defined $lp[$j] && $lp[$j] < $rp[$i] ){ (undef,@wanted) = @tokens[ $lp[$j] .. ($rp[$i] - 1 ) +] ; @tokens[ $lp[$j] .. ($rp[$i]) ] = \@wanted; push @temp, @wanted; $lp[$j] = $rp[$i] = undef; last; } } } return evaluate(\@tokens) ; } ################################################# sub evaluate { my $ops = shift; @$ops = grep { defined $_ } @$ops; foreach my $op (@$ops){ if (ref $op eq 'ARRAY'){ $op = evaluate($op); } } for (my $i=1; $i<$#{$ops}; $i++){ if ( index (" + - * / ^ = ", $ops->[$i]) > -1 ){ my $op = [@$ops[ $i, $i-1,$i+1]]; splice @{$ops}, $i - 1, 3 , $op; $i--; } } my $operator = shift @$ops; $operator = evaluate($operator) if ref $operator eq 'ARRAY'; if (defined $operator){ if (defined $Operators{$operator}){ $ops = $Operators{$operator}->(@$ops); }elsif($operator && @$ops ){ warn "Invalid expressions"; return; }else{ return $operator; } } return $ops; } ################################################# sub getsymbolval{ no strict; my @syms = @_; foreach my $symbol (@syms){ if ($symbol=~/^\D+$/){ $symbol = ${'Expression::Evaluate::'.$symbol}; } } wantarray ? @syms : $syms[0]; }
-Lee

"To be civilized is to deny one's nature."

In reply to Critique : Evaluating expressions. by shotgunefx

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.