D
doolittle
Hi,
I have to check that some input conforms to some rules. Although the
rules are simple to expain, my perl function looks too complex/long,
can it be done more simply?
The rule is that the first character must be a letter, and the second
and third characters must form a number between 1 and 25 (so the third
character is optional)
sub isOK {
my $str = shift;
# get the first character
my $chr = lc substr $str, 0, 1;
# return false if the first character is not a letter between a and Z
return 0 if $chr !~ /[a-z]/o;
# get the second character
$chr = substr $str, 1, 1;
# return false if the second character is not
# a number between 1 and 9
return 0 if $chr !~ /[1-9]/o;
# get the third character
$chr = substr $str, 2, 1;
if ($chr) {
# return false if the third character exists, but is not a number
return 0 if $chr !~ /\d/o;
# return false if the combination of the 2nd and
# 3rd characters is over 25
return 0 if (substr $str, 1) > 25;
}
# otherwise return true
return 1
}
I have to check that some input conforms to some rules. Although the
rules are simple to expain, my perl function looks too complex/long,
can it be done more simply?
The rule is that the first character must be a letter, and the second
and third characters must form a number between 1 and 25 (so the third
character is optional)
sub isOK {
my $str = shift;
# get the first character
my $chr = lc substr $str, 0, 1;
# return false if the first character is not a letter between a and Z
return 0 if $chr !~ /[a-z]/o;
# get the second character
$chr = substr $str, 1, 1;
# return false if the second character is not
# a number between 1 and 9
return 0 if $chr !~ /[1-9]/o;
# get the third character
$chr = substr $str, 2, 1;
if ($chr) {
# return false if the third character exists, but is not a number
return 0 if $chr !~ /\d/o;
# return false if the combination of the 2nd and
# 3rd characters is over 25
return 0 if (substr $str, 1) > 25;
}
# otherwise return true
return 1
}