Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: my program will not display a correct answer, to a random question?

by ig (Vicar)
on Aug 05, 2011 at 09:08 UTC ( #918707=note: print w/ replies, xml ) Need Help??


in reply to my program will not display a correct answer, to a random question?

I find it helpful to write programs that handle all possible input, processing expected input as required and giving error messages when unexpected input is received. In your case, you might have written your program as follows:

use strict; use warnings; print "Type in a number: "; my $x = <>; chomp($x); die "ERROR: '$x' is not a number" unless($x =~ /^\d+$/); print "Type in another number: "; my $y = <>; chomp($y); die "ERROR: '$y' is not a number" unless($y =~ /^\d+$/); print "What would you like done?\n\nYour choice is:\n1) Add\n2) Subtra +ct\n3) Multiply\n4) Divide\n"; my $ask = <>; chomp($ask); if ($ask eq "Add") { my $z = $x + $y; print "$x + $y = $z"; } else { die "ERROR: '$ask' is an unknown operation"; }

With the input you show in your post, this program gives:

Type in a number: 4 Type in another number: 5 What would you like done? Your choice is: 1) Add 2) Subtract 3) Multiply 4) Divide 1 ERROR: '1' is an unknown operation at ./test.pl line 23, <> line 3.

This may not be the "correct answer", but it may help you understand what is wrong.


Comment on Re: my program will not display a correct answer, to a random question?
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://918707]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (11)
As of 2014-07-25 07:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (169 votes), past polls