## A simple calculator

This is a simple calculator that sits in the gap between feature-light programs like windows calculator and the high overhead of a full on spreadsheet.

### Usage

The program reads equations from the standard input, and prints the answer, much as any calculator does.

1 =1 +2 =3 +3 =6 4 =4 +5 =9 1+7*(1+7*7*(1+7)) =2752

### Code for calc.pl:

#!/usr/local/bin/perl -w # # (C)opyright Ben Aveling 2012 # This script may be reproduced freely. # # ################# # General Behaviour # ################# # # This program tries to calculate whatever it is passed and print the result # It assumes that any line starting with +,-,*,... is a continuation of # the previous calculation # # ####### # History # ####### # # 2012.10.25 First published version # $SIG{__WARN__} = sub { die $_[0], "\n" }; $result = 0; while($equation=<>) { next if $equation =~ m/^\s*#|^\s*$/; $equation = $result . $equation if defined $result && $equation =~ m{^\s*[+-/\*]}; $result = eval($equation)||0; if(!$@){ print "=$result\n"; }else{ my $error=$@; $error=~s/ at \(eval \d+\) line \d+(, <> line \d+)?//g; print "Error: $error"; } }

### Commentary:

All the heavy lifting is done by the eval command. The rest is error handling, plus an attempt to work out if the result of the previous calculation should be kept as an input into the next calculation.

### Puzzle

What is 2752?

Advertisements