Input error handling

M

MJS

After the execution of the following, the only value I need in
"number" should be any positive interger(i.e any whole numbers without
zero).

print "Please enter a natural number = ";
chomp( my $number = <STDIN> );

I need to throw an exception or inform the user when input is anything
(characters, real number, negative number etc.) other the positve
integer. Please help.
 
E

Eric J. Roode

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

MJS wrote:

(snipped)

....
Your parameters are, paraphrased:

Any whole number which does NOT include a zero.

if ($number =~ tr/1-9// != length ($number))
{ print "FUBAR"; }
(the above modified to include your followup correction)

First, the number 109 is a positive integer, and one which the OP
presumably wants to allow, yet it fails your test.

Second, what an odd way of checking that a number contains only digits.
Count the digits, and check to see whether that count is equal to the
length of the number. Why not simply look for non-digit characters in
the string?

if ($number !~ /\D/ && $number != 0)
{ print "It's good!" }

- --
Eric
$_ = reverse sort $ /. r , qw p ekca lre uJ reh
ts p , map $ _. $ " , qw e p h tona e and print

-----BEGIN PGP SIGNATURE-----
Version: PGPfreeware 7.0.3 for non-commercial use <http://www.pgp.com>

iQA/AwUBP3Fy6GPeouIeTNHoEQIn6gCfVe+m8nF+5lBspooP2fb5xUowmlQAoOdK
vbAJ8j9ImiQyUVOBUABh0H2r
=cUU8
-----END PGP SIGNATURE-----
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top