Skip to content

Commit 793c1ed

Browse files
authored
maze: reject fractional width/height
* The size of the maze is counted in whole numbers; fractions don't maze sense * get_number() is used for input validation * Make get_number() reject the input if the number contains non-digits * Numbers don't allow a '+' prefix as in some commands * If EOF was seen when prompting for a number, terminate the program * test1: "perl maze 11 11" --> valid, no prompt * test2: "perl maze 12.34 12.6666666666666666666" --> invalid, will prompt for width & height
1 parent 5c0679f commit 793c1ed

File tree

1 file changed

+22
-7
lines changed

1 file changed

+22
-7
lines changed

bin/maze

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,29 @@ usage() if @ARGV;
5151

5252
sub get_number {
5353
my ($prompt, $value) = @_;
54-
55-
while (!defined($value) or $value < 2) {
56-
(defined $value) and ($value < 2) and print "$prompt too small.\n";
57-
print "$prompt? ";
58-
chomp($value = <STDIN>);
54+
my $regmatch = 0;
55+
my $inrange = 0;
56+
57+
until ($regmatch && $inrange) {
58+
if ($value =~ m/\A[0-9]+\Z/) {
59+
$regmatch = 1;
60+
} else {
61+
print "expected an integer value, got '$value'\n";
62+
}
63+
if ($regmatch) {
64+
if ($value >= 2) {
65+
$inrange = 1;
66+
} else {
67+
print "$prompt too small\n";
68+
}
69+
}
70+
if (!$regmatch || !$inrange) {
71+
print "$prompt? ";
72+
chomp($value = <STDIN>);
73+
die "unexpected eof\n" unless defined $value;
74+
}
5975
}
60-
61-
$value;
76+
return $value;
6277
}
6378

6479
$width = &get_number('width', $width);

0 commit comments

Comments
 (0)