# checkmath.pl
# This script reads in a series of arithmetic statments, 
# and checks whether they are correct
# It is extremely limited, in that it only handles statements with 2 operands

$input_file = "math.txt";
open (INFILE, $input_file) or die "Can't open input file: $!\n";

$correct_answers = 0;
$incorrect_answers = 0;

CHECK_ANSWER:
while ($line = <INFILE>) {
    chomp($line);
    # We'll assume that statements have the form:
    #      x OPERATION y = z 
    # So, let's first start by getting the left sides and result.
    # We can split at the equal sign (removing also any spaces around it
    ($operation, $given_answer) = split(/\s*=\s*/,$line);
    
    # Now, the trick is to parse out the operation, so we can check it
    # We want to split at a +, -, * or /
    # Since these are all "special" symbols in regular expression syntax,
    # we need to "protect" them by putting a backslash before each.
    # As before, we also include the spaces (\s*) as part of the delimiter
    @operands = split(/\s*[\+\-\*\/]\s*/, $operation);        
    
    if ($operation =~ /\+/) {
	$operator = "plus";		
	$real_answer = $operands[0] + $operands[1];
	
    } elsif ($operation =~ /\-/) {
	$operator = "minus";		
	$real_answer = $operands[0] - $operands[1];	
    } elsif ($operation =~ /\*/) {
	$operator = "times";		
	$real_answer = $operands[0] * $operands[1];	
    } elsif ($operation =~ /\//) {
	$operator = "divided by";		
	$real_answer = $operands[0] / $operands[1];	
    } else {
        # If we got here, there was no +, -, *, or / found
        print "Error! The operation $operation was not found to have an operator\n";
	next CHECK_ANSWER;		
    }        
    
    if ($real_answer == $given_answer) {
	$correct = 1;
	$correct_answers++;	    	    
    } else {
	$correct = 0;
	$incorrect_answers++;	    	    
    }
    print "$operands[0] $operator $operands[1] is $real_answer\t";	
    print "\t(The given answer of $given_answer is ";	
    unless ($correct) { print "NOT "; }
    print "correct)\n";		
        
}

# We are now done with the file, and can calculate summary statistics.
print "\nTotal of $correct_answers correct answers, and $incorrect_answers incorrect answers.\n";
print "\t(Overall score: " . ($correct_answers * 100 / ($correct_answers + $incorrect_answers))." percent)\n";
