Database Reference
In-Depth Information
do this, match only the initial part of the string (omit the $ that requires the pattern to
match to the end of the string) and place parentheses around the \d+ part. Then refer
to the matched number as $1 after a successful match:
if ( $val =~ /^(\d+)/ )
{
$val = $1 ; # reset value to matched subpart
}
You could also add zero to the value, which causes Perl to perform an implicit string-
to-number conversion that discards the nonnumeric suffix:
if ( $val =~ /^\d+/ )
{
$val += 0 ;
}
However, this method of discarding trailing nonnumeric characters has a disadvantage:
the conversion generates warnings for values that actually have a nonnumeric part if
you run Perl with the -w option or include a use warnings line in your script (which I
recommend). It also converts string values like 0013 to the number 13 , which may be
unacceptable in some contexts. See Recipe 2.4 for additional discussion and an alter‐
native approach.
Some kinds of numeric values have a special format or other unusual constraints. Here
are a few examples and how to deal with them:
ZIP codes
ZIP and ZIP+4 codes are postal codes used for mail delivery in the United States.
They have values like 12345 or 12345-6789 (that is, five digits, possibly followed by
a dash and four more digits). To match one form or the other, or both forms, use
the patterns shown in the following table:
Pattern Type of value the pattern matches
/^\d{5}$/ ZIP code, five digits only
/^\d{5}-\d{4}$/ ZIP+4 code
/^\d{5}(-\d{4})?$/ ZIP or ZIP+4 code
Credit card numbers
Credit card numbers typically consist of digits, but it's common for values to be
written with spaces, dashes, or other characters between groups of digits. For ex‐
ample, the following numbers are equivalent:
0123456789012345
0123 4567 8901 2345
0123-4567-8901-2345
To match such values, use this pattern:
 
Search WWH ::




Custom Search