Sample Exercises
Subroutines: Calculator
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
SolutionLast updated:
Copyright © 1995-2008 William R. Ward dba Bay View Training. All Rights Reserved. “Bay View Training”, “Bay View Consulting Services”, “Bay View Software”, the sailboat logo, and the domain name “bayview.com” are trademarks and/or service marks of William R. Ward dba Bay View Training. For more information, contact training@bayview.com
