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

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; }