Assignment #6


It's now time to write some stuff in Perl to play with strings and files. The most powerful manipulations will come in the next assignment when we have talked about regular expressions. For right now we just want to do some basic stuff to see if you understand working in Perl.

Write a reverse Polish caluclator in Perl. This can take input from a file or standard input as provided on the command line. Since we haven't learned how to pick strings apart in Perl, we'll keep it simple. The input will have one number or operation on each line. So to do the calculation 5*(3+4) your file would be as follows

3
4
+
5
*

The way to implement this type of calculator is with a "stack". Each time you hit a value you push that value onto the stack. Each time you hit an operation, pop of the operands, do the operation, and push the result back on. Feel free to play around and try to put in other operations. You need to have +, -, *, and /.

Once you have that done, I want you to try to put in a little twist: variables. If a line starts with = then what follows it is a variable name. The top of the stack should be popped and that value should be "assigned" to the proper variable. Having a variable name on a line should look up that value and push it on the stack just like a number. So the following file contents would have a value of 5 at the end with A being 2 and B being 3.

2
=A
3
=B
A
B
+

This is challenging given what you have learned so feel free to submit your assignment without it working, but at least try it. You'll be able to to this a lot better after we have learned how to do regular expressions.