If you must validate user input, it is worth using a prompt module. It not only detects the errors, it gives the user a chance to correct them.
#!/usr/bin/perl
use strict;
use warnings;
use IO::Prompt::Hooked;
my $days = prompt(
message => "Enter no of days older (1-90):",
error => "Invalid input, please try again\n",
validate => sub {
my $days = shift;
return ( $days =~ /^[1-9]\d?$/ and $days <= 90 );
},
);
print "You entered $days days\n\n";
The following sample run shows the recovery from several errors.
:tt.pl
Enter no of days older (1-90): a
Invalid input, please try again
Enter no of days older (1-90): !
Invalid input, please try again
Enter no of days older (1-90): 333
Invalid input, please try again
Enter no of days older (1-90): 99
Invalid input, please try again
Enter no of days older (1-90): 07
Invalid input, please try again
Enter no of days older (1-90): 9
You entered 9 days
:
|