Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

How can I validate user input?

by Buckaroo Buddha (Scribe)
on May 10, 2000 at 19:40 UTC ( [id://10974]=perlquestion: print w/replies, xml ) Need Help??

Buckaroo Buddha has asked for the wisdom of the Perl Monks concerning the following question:

I've tried:
$start = $ARGV[0]; if ($start eq '') { $start = &get_start_level; } sub get_start_level { print "Please Enter the Start-Level (0-7,?)[0]: "; $input = <>; # clear all but numbers or '?' #if ($input ne '?') { # $input =~ tr/!(0-9)//\d; #} if ($input eq '?') { print " **** internally coded help information **** \n"; print " **** internally coded help information **** \n"; $input = &get_start_level; } elsif (($input < 0) || ($input > 7)) { print "please enter a number that is between Zero and Seven\n"; $input = &get_start_level; } return ($input); } =========================== end code ============
This seems to me like a pretty straight forward problem. What am i doing wrong? ... I can't seem to figure this out.

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How can I validate user input?
by ton (Friar) on Apr 05, 2001 at 03:56 UTC
    while ($start !~ /^[0-7]$/) { print "Please Enter the Start-Level (0-7,?)[0]: "; $start = <STDIN>; chomp $start; if ($start eq '?') { print "Some help info.\n"; } }
Re: how do i work this
by Russ (Deacon) on May 12, 2000 at 06:17 UTC
    Here's one way to do this:
    my $start = $ARGV[0]; while (1){ print "Please Enter the Start-Level (0-7,?)[0]: "; chomp($start = <>); # Check for non-numeric characters if ($start =~ /\D/){ print "\nPlease enter a number (0-7) or ? for help\n"; next; } last if 0 <= $start and $start <= 7; # Check for a help request if ($start eq '?') { print " **** internally coded help information **** \n"; next; } print "\nPlease enter a number between Zero and Seven, inclusive\n"; } print $start;
    First, we check that the input is numeric (as you started to do in your commented-out code) to prevent errors if the user enters non-numeric characters.
    If the input is valid, we just exit the loop.
    If not, check for a help request and, if not '?', print a generic error message and redo the loop.

    There are a million different ways to do this, and this is only one of them...

    Russ

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (7)
As of 2024-04-18 07:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found