Obviously we need some kind of looping structure to reprompt the user. A while() is the right choice here. When you design a while() loop, you want to put the terminating condition of the loop right there at the beginning of the loop instead of using while(1){...some buried termination condition in body somewhere}. I don't want to go looking down through a bunch of code to figure out how the loop stops! In the code below, typing "q,QUIT,qUIt, etc, stops the loop.
Now we want to do something else: get the loop initialized and re-initialized for each iteration. I could have put a print above the loop for the first prompting and then put some other print inside the body of the loop for re-prompting, but the easy way to do this is to put the prompting in the while() condition! The while loop only takes a single statement. So the way to do this is with the "comma" operator. This allows combining what normally would be two different statements into one. The loop termination condition that is being tested is only the very last part of the statement, the regex. I have on occasion come across situations where 3 things are in the loop condition, but usually just 2 like below is just fine.
A "blank" input should not be an error, just a reprompt. I check for that early and use "next" to restart the loop if that is the case. For the other conditions, I like the if (condition){err msg, next;} structure versus some complex if(),elseif(),else() deal. One reason is that this allows me to easily move the order of the conditions around (nothing special about the first one, middle one or last one). Then the last thing we do of course is some actual operation on the data that we've just validated.
Update:#!/usr/bin/perl -w use strict; while ( (print "Enter Date: "), (my $date =<STDIN>) !~ /^\s*q(uit)?\s*$/i ) { next if $date =~ /^\s*$/; # reprompt on blank line chomp($date); if ($date =~ m|[^\d/]|) { print "Valid date has only digits and /!\n"; next; } #....more valdiation here .... #then actually do something before reprompting }
I presented a more general sort of a thing than perhaps you need for just entering and validating a couple of inputs. Something like below could be setup so that it just keeps re-prompting user for a date and doesn't give up until you get a valid date. You write the "ok" routines so that they output any necessary error messages to the user and return false until you get something that you like. I would imagine that they both call some common format validation for whatever format you need. Now that you see the idea of the technique, you can adapt it to your specific needs.
my $start_date; my $end_date; while (print "Enter start date: ",!start_date_ok(<STDIN>)); while (print "Enter end date: ", !end_date_ok (<STDIN>));
In reply to Re: Handling User Input
by Marshall
in thread Handling User Input
by cheech
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |