Refine the get_string example to accept only integers. It should accept three pa
ID: 3561138 • Letter: R
Question
Refine the get_string example to accept only integers. It should accept three parameters: the prompt string, a lower limit on the acceptable integers, and an upper limit on the acceptable integers. Accepting and validating input The script below combines many of the Perl constructs we've reviewed over the last few pages, including a subroutine, some postfix if statements, and a for loop. The program itself is merely a wrapper around the main function get_string, a generic input validation routine. This routine prompts for a string, removes any trailing newline, and verifies that the string is not null. Null strings cause the prompt to be repeated up to three times, after which the script gives up.Explanation / Answer
#!/usr/bin/perl
sub get_string {
my ($promptStr, $minV, $maxV) = @_;
print "$promptStr: ";
my $number = <STDIN>;
chomp($number);
if($number =~ /^d+$/) {
if($number >= $minV && $number <= $maxV) {
print "$number is a valid integer in the range "."$minV - $maxV";
}
else {
print "Enter a valid integer in the range $minV - $maxV";
}
} else {
print "Enter integer only";
}
}
my $min = 1;
my $max = 50;
my $prompt = "Enter an ineger between $min and $max";
#If you need you can get $prompt, min and max values from user like below
# print "Enter prompst string ";
# $prompt = <STDIN>;
# print "Enter minimum value ";
# $min= <STDIN>;
# print "Enter max value ";
# $max= <STDIN>;
get_string("$prompt", $min, $max);
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.