in reply to a timid approach to parsing arithmetic expressions in perl

I was testing something else, when I discovered an expression that generates tons of warnings:

my $exp = 3-(4+5);

I'd also be interested in seeing a right-associative operator added.

my $exp = 4**3**2; # = 4**9 = 262144

Replies are listed 'Best First'.
Re^2: a timid approach to parsing arithmetic expressions in perl
by spx2 (Deacon) on Jul 26, 2008 at 15:25 UTC
    Hi ikegami and thank you very much for the interest in this,

    Using minor modifictions I've implemented also POW for this evaluator
    I've also added as a test the expression "3**(6-1*4)**2" which should eval to 81.
    About the warnings , the compiler already evaluated the expression to -6 and the bug
    was caused by the fact that negative numbers were not yet recognised.
    Now both of these are fixed.

      3**(6-1*4)**2 is a bad test since (3**2)**2 happens to equal 3**(2**2)

      When I use the 3**4**2 I had previously mentioned, your code returns 6561 ((3**4)**2) instead of 43046721 (3**(4**2)).

      >perl -le"print 3**4**2" 43046721
      hmm,seems that the right associative operator must be parsed in a different way...
      the problem about evaluating "3**4**2" still persists ...
      however if paranthesis are employed and we re-write like this "3**(4**2)" it will be evaluated correctly.
      uhm,the only way I can see this as beeing done is by using a stack and putting all 3,4,2 on it
      if the operator ** is found and afterwards start emptying the stack by taking two of them,evaling
      putting them back and so on.