in reply to Chomp a numerical expression, return the answer.

EDIT: I'm an idiot--. I don't know how I messed up the code that badly. Yes, order from left to right does matter (at least for multiplication / division). Here's the fixed version:
use strict; use warnings; while (<DATA>) { chomp; print process($_), "\n"; } sub process { my $exp = $_[0]; 1 while $exp =~ s/\(([^(]*)\)/reduce($1)/eg; $exp = reduce($exp); $exp =~ s/\s+//g; return reduce($exp); } sub reduce { my $exp = $_[0]; 1 while $exp =~ s{(\d+)\s+([*/])\s+(\d+)} {$2 eq '*' ? $1*$3 : $1/$3}e; 1 while $exp =~ s{(\d+)\s+([+-])\s+(\d+)} {$2 eq '+' ? $1+$3 : $1-$3}e; return $exp; } __DATA__ (7 * 3) + (2 + 1) 4 * (5 / (3 + 2)) - 6 2 * 2 * 2 8 / 2 * 3

Replies are listed 'Best First'.
Re^2: Chomp a numerical expression, return the answer.
by ikegami (Patriarch) on May 18, 2006 at 19:45 UTC

    Your code doesn't support 2 * 2 * 2 and returns the wrong answer for 8 / 2 * 3. Fix:

    sub reduce { my $exp = $_[0]; 1 while $exp =~ s{(\d+)\s+([*/])\s+(\d+)} { $2 eq '*' ? $1*$3 : $1/$3 }e; 1 while $exp =~ s{(\d+)\s+([+-])\s+(\d+)} { $2 eq '+' ? $1+$3 : $1-$3 }e; return $exp; }