Database Reference
In-Depth Information
$val =~ s/^\s+// ; # trim leading whitespace
$val =~ s/\s+$// ; # trim trailing whitespace
That's such a common operation, in fact, that it's a good candidate for being written as
a utility function. The Cookbook_Utils.pm file contains a function trim_white
space() that performs both substitutions and returns the result:
$val = trim_whitespace ( $val );
To remember subsections of a string matched by a pattern, use parentheses around the
relevant pattern parts. After a successful match, you can refer to the matched substrings
using the variables $1 , $2 , and so forth:
if ( "2019-05-23" =~ /^(\d+)(.*)$/ )
{
$first_part = $1 ; # this is the year, 2019
$the_rest = $2 ; # this is the rest of the date
}
To indicate that an element within a pattern is optional, follow it with a ? character. To
match values consisting of a sequence of digits, optionally beginning with a minus sign,
and optionally ending with a period, use this pattern:
/^-?\d+\.?$/
Use parentheses to group alternations within a pattern. The following pattern matches
time values in hh:mm format, optionally followed by AM or PM :
/^\d{1,2}:\d{2}\s*(AM|PM)?$/i
The use of parentheses in that pattern also has the side effect of remembering the op‐
tional part in $1 . To suppress that side effect, use (?: pat ) instead:
/^\d{1,2}:\d{2}\s*(?:AM|PM)?$/i
That's sufficient background in Perl pattern matching to enable construction of useful
validation tests for several types of data values. The following sections provide patterns
that can be used to test for broad content types, numbers, temporal values, and email
addresses or URLs.
The transfer directory of the recipes distribution contains a test_pat.pl script that reads
input values, matches them against several patterns, and reports which patterns each
value matches. The script is easily extensible, so you can use it as a test harness to try
your own patterns.
12.4. Using Patterns to Match Broad Content Types
Problem
You want to classify values into broad categories.
Search WWH ::




Custom Search