both replies above have good advice .. reading through your code I envisioned slightly different code reduction/dispatch tables and thought I'd share in the spirit of
TMTOWTDI (a term which, if you haven't seen by name i'm sure you've already seen in use)
One thought, was no need to use numbers in your menu -- just have them enter the operation. And in general, I like to have one printf statement if they're all similar in form -- this separates content from logic and makes it much easier to modify in the future.
# input num1
# input num2
# First, setup a hash that defines what's can be done and it's attribu
+tes.
my %ops = (
'+' => { label => 'Sum' },
'-' => { label => 'Difference' },
'*' => { label => 'Product' },
'/' => { label => 'Division' },
'M' => { label => 'Multiplication', table => 1, op => '*' },
);
while (1){ #adding a loop around this
# using a here-doc to do the output
print <<EOS;
Please enter the Maths that you want to perform:
+ - * /
M = Mulitiplication Table
EOS
chomp($sign=<STDIN>);
last if exists $ops{$sign}; # see if we got something that we confi
+gured in the hash
}
my $op = $ops{$sign};
if( $op->{table} ){
printf "the %s Table For %d and %d is \n", $op->{label}, $num1, $num
+2;
printf("%d %s %d = %f\n", $_, $op->{label}, $num1, eval($_.$op->{op}
+.$num1) ) for 1 ..$num2;
}else{
printf "The %s of the Numbers %d %s %d is %f\n",
$op->{label},
$num1, $sign, $num2,
eval "$num1 $sign $num2",
;
}
Notice, for example, how trivial it is to change the output (e.g. "____ of the numbers" to "___ for") or to extend it (e.g. add an option to display the Addition table).
one caveat about
eval -- it's use here is ok becuase the input had been checked, so we know it's _only_ got a few (safe) values. A more robust dispatch table could provide the actual subroutine to call (
Super Search for 'dispatch table' and 'function references' for more)
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.