Sample Exercises

Subroutines: Calculator

Return to exercise list

Write a 4-function calculator, starting with the "stub" program listed below, which reads from <> until either end-of-file or the string "exit" is reached. Each line of input consists of two numbers separated by one of the operators +, -, *, or /. There may or may not be spaces at the beginning and/or end of the line, or before and/or after the operator - ignore any such spaces if found. Start with the stub program provided (see Auxiliary Files below), and add the subroutines parse_line() and calculate() to complete it.

Inside the parse_line() subroutine, you should split the line using a regular expression and return the operator and the two numbers found (in that order).

Inside the calculate() subroutine, do the appropriate calculation and return the result. Note that dividing by zero is an error which Perl will automatically detect, causing the program to exit with an error message.

Auxiliary File for Calculator

Solution for Calculator

Solution