Below, ask_yes_no("prompt XXX") keeps prompting with "prompt XXX" until either a 'Y' or a 'N' answer happens or a quit/abort input is seen which causes the program to completely stop.
A non-answer (blank line) causes just a re-prompt (that's not an error as per standard CLI).
An invalid answer causes an error message and then the re-prompt.
Of course it would be possible to tighten the while loop up so much that it only allows 'Y' or 'N' for the $answer.
The basic idea when prompting the user for an answer:
1) ask the question
2) a "non answer" like a bunch of blanks is ok, just re-prompt
3) an "illegal answer".. something that is clearly wrong should
result in an error message and then the re-prompt
4) spaces before or after the "answer" should be meaningless.
In the code below, there are a number of lines of "boiler plate" stuff along the way to returning a Y or a N. It is not necessary to reduce this to the minimum number of lines of code. The computer is ridiculously fast compared with the human being. And sometimes fewer lines of source code does not mean a faster program.
I would advocate something like the below. Ask the question and if the subroutine returns, it has a Y or a N. If it cannot come back with one of those 2 answers, then it should not "come back" to the main program.
#!/usr/bin/perl -w use strict; my $answer = ask_yes_no ("Gimme a Yes or No!(Y/N)?"); print "answer = $answer\n"; sub ask_yes_no { my $prompt = shift; while ( (print $prompt), (my $answer = <STDIN>) !~ /^\s*q(uit)?\s*$|^\s*abort\s*?/i + ) { next if $answer =~ /^\s*$/; # re-prompt on blank line $answer =~ s/^\s*//; #no leading spaces $answer =~ s/\s*$//; #no trailing spaces $answer = uc $answer; return $answer if ($answer eq 'Y' or $answer eq 'N'); print "Illegal entry try again..!!\n"; } die "quit or abort was entered! **Abort Program!!**\n"; } __END__ Example: UI test run.... C:\TEMP>perl askyn.pl Gimme a Yes or No!(Y/N)?2345 Illegal entry try again..!! Gimme a Yes or No!(Y/N)?y answer = Y C:\TEMP>perl askyn.pl Gimme a Yes or No!(Y/N)?N answer = N C:\TEMP>perl askyn.pl Gimme a Yes or No!(Y/N)?a Illegal entry try again..!! Gimme a Yes or No!(Y/N)?ABORT quit or abort was entered! **Abort Program!!** C:\TEMP>perl askyn.pl Gimme a Yes or No!(Y/N)?Q quit or abort was entered! **Abort Program!!** C:\TEMP>perl askyn.pl Gimme a Yes or No!(Y/N)? Gimme a Yes or No!(Y/N)? Gimme a Yes or No!(Y/N)? Gimme a Yes or No!(Y/N)?
In reply to Re: Silly While Loop Problems
by Marshall
in thread Silly While Loop Problems
by gsus
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |