Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Write a program called calculate.pl which will operate as a primitive calculator operating on a single number (the 'accumulator') whose value may be modified by user commands. The program should meet the following requirements:
When called with arguments, interprets them as names of files containing commands.
When called without arguments, reads commands from standard input. You may find it easy or at least entertaining to run the program in this mode.
Commands are lines that match one of the following patterns:
The intended effects of those commands can be seen in the following capture of program interaction. User input is EQUALS, CLEAR, PLUS, OVER, TIMES, MINUS. The accumulator starts out undefined.
calculate.pl dialog $ ./calculate.pl EQUALS (undefined) OK CLEAR OK EQUALS = 0 OK PLUS 42 OK EQUALS = 42 OK OVER 7 OK TIMES 3 OK MINUS 3 OK EQUALS = 15 OK explode Invalid statement
You can assume that there is exactly one space between the operator and the number in valid commands. You do not have to trap division by zero or warnings about operating on an undefined accumulator.
Use subroutines to keep the length of the main program and each of the subroutines below a standard screen (24 lines) at one statement per line.
Output a prompt string "> " before each input, like so: calculate.pl dialog
$ ./calculate.pl > EQUALS (undefined) OK > CLEAR OK > EQUALS = 0 OK > PLUS 42 OK > EQUALS = 42 OK > OVER 7 OK > TIMES 3 OK > MINUS 3 OK > EQUALS = 15 OK > explode Invalid statement >
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is what I have so far:
#!/usr/bin/perl use strict; use warnings; my $total; print "> "; while(my $line = <>){ chomp $line; my ($cmd, $num) = split " ", $line, 2; process($cmd,$num,$total); print "OK\n\>"; } sub process{ my($cmd,$num,$total) = @_; print "COMMAND: $cmd, VALUE: $num, TOTAL: $total \n"; }
I'm not planning on proceeding with learning much more Perl, however, I would just like to see how this project can be accomplished for piece of mind. Any help would be greatly appreciated!
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Calc Help
by MidLifeXis (Monsignor) on Aug 19, 2014 at 17:12 UTC | |
|
Re: Calc Help
by Anonymous Monk on Aug 19, 2014 at 18:21 UTC | |
by Anonymous Monk on Aug 19, 2014 at 19:46 UTC |