Database Reference
In-Depth Information
{
# $val didn't match ISO format pattern
}
You'll often find additional processing necessary with dates because date-matching pat‐
terns help to weed out values that are syntactically malformed, but don't assess whether
the individual components contain legal values. To do that, some range checking is
necessary. Recipe 12.11 covers that topic.
If you're willing to skip subpart testing and just want to rewrite the pieces, use a
substitution. For example, to rewrite values assumed to be in MM-DD-YY format into YY-
MM-DD format, do this:
$val =~ s/^(\d+)\D(\d+)\D(\d+)$/$3-$1-$2/ ;
Time values are somewhat more orderly than dates, usually being written with hours
first and seconds last, with two digits per part:
/^\d{2}:\d{2}:\d{2}$/
To be more lenient, permit the hours part to have a single digit, or the seconds part to
be missing:
/^\d{1,2}:\d{2}(:\d{2})?$/
Mark parts of the time with parentheses if you want to range-check the individual parts,
or perhaps to reformat the value to include a seconds part of 00 if it happens to be
missing. However, this requires some care with the parentheses and the ? characters in
the pattern if the seconds part is optional. You want to permit the entire :\d{2} at the
end of the pattern to be optional, but not to save the : character in $3 if the third time
section is present. To accomplish that, use (?: pat ) , a grouping notation that doesn't
save the matched substring. Within that notation, use parentheses around the digits to
save them. Then $3 is undef if the seconds part is not present, and contains the seconds
digits otherwise:
if ( $val =~ /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/ )
{
my ( $hour , $min , $sec ) = ( $1 , $2 , $3 );
$sec = "00" if ! defined ( $sec ); # seconds missing; use 00
$val = "$hour:$min:$sec" ;
}
To rewrite times from 12-hour format with AM and PM suffixes to 24-hour format, do
this:
if ( $val =~ /^(\d{1,2}):(\d{2})(?::(\d{2}))?\s*(AM|PM)?$/i )
{
my ( $hour , $min , $sec ) = ( $1 , $2 , $3 );
# supply missing seconds
$sec = "00" unless defined ( $sec );
if ( $hour == 12 && ( ! defined ( $4 ) || uc ( $4 ) eq "AM" ))
{
Search WWH ::




Custom Search