Databases Reference
In-Depth Information
input is what you expect. This is typically performed using regular expressions , where
we match a string against a template.
For example, we can ensure that the form variable Age is a number between 10 and 99:
if(param())
{
if(!(param('Age')=~/^([1-9][0-9])$/))
{
print
font({-color=>'red'}, 'Invalid age: must be between 10 and 99 inclusive.');
exit;
}
my $user_age = "$1";
print $user_age;
}
Perl offers some cryptic syntax for regular expressions, but they make the expressions
very easy to integrate into a program. The =~ operator means “check the item on the
left against the regular expression on the right.” The regular expression itself is enclosed
in forward slashes, although you can choose another character if you find this incon-
venient (for instance, if the regular expression itself contains a slash). Thus, the if
statement just shown checks whether the Age parameter matches the regular expres-
sion /^([1-9][0-9])$/ . The expression itself is simpler than it at first appears.
The numbers in the brackets express a range. Here, we want two digits: the first between
one and nine, and the second between zero and nine. The parentheses delimit the part
of the string that matches these two characters. The caret ( ^ ) symbol marks the start of
the string, and the dollar ( $ ) symbol marks the end of the string; together, these two
anchors ensure that there's nothing before or after the two digits. After the regular
expression check, the substring enclosed in the first set of parentheses is available as
$1 , the substring enclosed between the second set of parentheses is available as $2 , and
so on. We can assign this to a variable and use it; here, we're just printing it on the
screen. If the check fails, we print an error message and stop the program with the
exit keyword. Note that the die( ) function won't produce the display you want in a
web environment because its message is sent to the system standard error location,
rather than to standard output.
As another example, we can check that an entered name is less than 10 characters long
and that only its first letter is capitalized; we allow an initial character in the range
A-Z , and between 0 and 9 characters in the range a-z :
if(param())
{
if(!(param('Name')=~/^([A-Z][a-z]{0,9})$/))
{
print
font({-color=>'red'},
'Invalid name: must comprise only letters, '.
'be at most ten characters long, ',
'and have only the first letter capitalized.');
 
Search WWH ::




Custom Search