shotgunefx has asked for the wisdom of the Perl Monks concerning the following question:

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."

Replies are listed 'Best First'.
Re: Critique : Evaluating expressions.
by belg4mit (Prior) on Sep 25, 2002 at 05:13 UTC
    I suggest PEMDAS and not simple left-to-right. You might also look at Math::Expr.

    --
    perl -pew "s/\b;([mnst])/'$1/g"

      I probably will add correct precedence when I have less "real work" to do. I mainly did this as an exercise. It was a different type of problem then I normally solve.

      For me the grouping by parens and constructing an "op" tree was a real tricky problem so I just had to beat my head off the wall until I figured it out.
      Update
      Done PEMDAS ordered. Assignment propagates left. i.e a=b=c=10 will assign a,b,c the value 10.
      Code follows below.