Here is a simple formula for a command loop. For user input any leading and trailing spaces are allowed (just like std unix commands). 1) print the prompt, 2)get the user line, 3) reject if it doesn't match the desired regex.
Note: the parens around the print are required.
I made the above into a sub, but I can't find it right now. Virtually none of my programs prompt the user for input in this way in preference to Getopt or Getopt::Long.use strict; use warnings; my $n_cookies; while ( (print "How many cookies do you want? Enter number: "), $n_cookies=<STDIN> and $n_cookies !~ /^\s*[1-9]\d*\s*$/) { print "invalid input! - try again!\n"; } $n_cookies +=0; # trick to convert to numeric value # which "deletes" leading/trailing zeroes # or a substitution operation would be fine print "$n_cookies cookies requested!"; __END__ Example Run: Note: allowing leading zero requires more complex regex This is just a "concept example" C:...\PerlProjects\Monks>perl commandloop.pl How many cookies do you want? Enter number: invalid input! - try again! How many cookies do you want? Enter number: 0 invalid input! - try again! How many cookies do you want? Enter number: 023 invalid input! - try again! How many cookies do you want? Enter number: 1 23 invalid input! - try again! How many cookies do you want? Enter number: abc invalid input! - try again! How many cookies do you want? Enter number: cookies 34 invalid input! - try again! How many cookies do you want? Enter number: 5 5 cookies requested!
In reply to Re^2: STDIN Enter key not quite working
by Marshall
in thread STDIN Enter key not quite working
by slugger415
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |