in reply to Homework: simple calculator

Well, that's a pretty ugly mess. ;)

You gain points for use strict;, but lose more for awful indentation. And actually it is that awful indentation that is the biggest reason you are having trouble with the code. Consider this re-indented version (some lines omitted):

#!/user/bin/perl -w use strict; my $quit = 0; print "Welcome to the mathq program\n"; until ($quit) { print "Enter a number\n"; my $first_number = <STDIN>; chomp ($first_number); if ($first_number eq 'q') { $quit = 1; } else { print "Enter a second number\n"; my $second_number = <STDIN>; ... } } if ($second_number != 0) { ... } elsif ($second_number == 0) { ... } else { print "Invalid input: Type a number or 'q' to quit\n"; }

note that the calculation code it outside the loop! Note too that the variables that are used for the calculation step are declared inside a block inside the loop - actually that's where they should be except that the calculation code is nowhere in sight. So, a little restructuring:

#!/user/bin/perl -w use strict; my $quit = 0; print "Welcome to the mathq program\n"; until ($quit) { print "Enter a number\n"; my $first_number = <STDIN>; chomp ($first_number); if ($first_number eq 'q') { $quit = 1; } else { print "Enter a second number\n"; my $second_number = <STDIN>; ... if ($second_number != 0) { ... } elsif ($second_number == 0) { ... } else { print "Invalid input: Type a number or 'q' to quit\n"; } } }

fixes the primary issue, but still leaves room for a lot of tidying. For example, $quit is not needed if instead you use last to exit the loop.

In general if you have code of the form:

if (...) { ... last; } else { ... }

you can restructure it as:

if (...) { ... last; } ...

If you have:

if (X) { ... } elsif (! X) { ... } else { ... }

there are two issues. The } elsif (! X) { can simply be } else {. But then it becomes obvious that the trailing else clause is bogus.

Final hint: if you find yourself writing the same code in several places then you can refactor the code in some fashion to remove the duplication. In this case the calculation code contains two groups of three lines that are the same in both cases so they can all be moved outside the if and just the special case code needs to be managed by the if.


Perl is environmentally friendly - it saves trees