#!/usr/bin/env perl -w print "Enter a formula, or 'done' to quit\n"; while (($formula = ) !~ /^done$/i){ chomp $formula; if ($formula !~ /^\s* #beginning of string (-?\d+(?:\.\d+)?) #possible negative, & numbers \s* ([\+\-\*\/%]) #operator \s* (-?\d+(?:\.\d+)?) #possible negative, & numbers \s*=\s* #spaces, =, spaces $/x){ #end of string print "That is not a valid formula\n"; print "Enter another formula, or 'done' to quit\n"; next; } #formula matched, now assign variables ($arg1, $op, $arg2) = ($1, $2, $3); #Special case for division if ($op eq '/'){ #Floating point division if (($arg1 =~ /\./) || ($arg2 =~ /\./)){ $sol = $arg1 / $arg2; } #Integer division else { $sol = int ($arg1 / $arg2); } } else { #anything else, just evaluate the mathematical sentence $sol = eval ("$arg1 $op $arg2"); #NOTE: I realize we did not yet mention the eval() function. #This function takes a string and evaluates it as perl code #I am using it here for brevity. However, if you were unaware #of this function's existance, it should be a trivial matter #to set the $sol using a series of if/elsif/else blocks instead } #Print the solution, and store the operators and solution in hashes print "$sol\n"; $solutions{$formula} = $sol; $operators{$formula} = $op; } #Get all the formulas, then sort them. #In the sort routine, if the first condition returns 0, (that is, the #operators are equal to each other, short circuit logic comes into play #with the 'or' operator, and the second condition is evaluated. If you #are confused by this, please email me. @all_forms = keys %solutions; @sorted = sort { ($operators{$a} cmp $operators{$b}) #sort first ASCIIbetically by operator or ($solutions{$b} <=> $solutions{$a}) #sort 2nd numerically by solution } @all_forms; #finally, print out all formulas and their solutions. print "\nAll formulas and their solutions are:\n"; foreach (@sorted){ print "$_ $solutions{$_}\n"; }