Pages

Checking user input

We are writing a Perl script, and we have to choose a execution path accordingly to the user decision. The user should answer y or n, both lower and uppercase, to our question. Any other answer has to be rejected.

Here is a possible solution to this common requirement.

The code that requires the user decision is something like that:
print "First step completed\n";
if(stop_execution()) # 1
{
print "Correct data and retry.\n";
exit 1; # 2
}
else
{
print "Ready for the next step.\n";
}

print "This is the second step.\n";

# ...

exit 0;

1. We are about to describe our decision-making function stop_execution() just below. Here it suffices noticing that it would return a "true" value in case we actually want to interrupt the execution stream.
2. As usually expected, a script returns a non-zero value in case of unhappy ending.

Our user interaction consists in asking if he is ready for the next step, iterating until his answer is a valid one, and returning to the user a true/false value:
sub stop_execution
{
my $prompt = "Do you want to continue? [y/n]: "; # 1

print $prompt;
while(<STDIN>) # 2
{
if(/^n$/i) # 3
{
return 1;
}
elsif(/^y$/i) # 4
{
return 0;
}
print $prompt; # 5
}
}

1. This is the string that will be used as prompt to the user to get an input.
2. We read from the standard input stream, and put the result in the default $_ variable.
3. If $_ is matching to the specified pattern, we return a non-zero value (that means, true). The pattern is just a letter, n, and we specify that the string should match to it from the beginning to its end. Besides, the 'i' character after the closing slash tells that the match is case-insensitive. So both "n" and "N" are accepted.
4. Same as above, but the pattern is matching against "y" (and "Y") and we return 0 (meaning false).
5. If the user input does not match with our expectations, we repeat the question and iterate.

No comments:

Post a Comment