How would you factorize (or not) the following line ?
if ($Hour =~ /^(\d{2})(\d{2})(\d{2})$/) { $result = "开发者_如何学JAVA$1:$2:$3" }
First off, don't use \d
unless you want to match all Unicode digit characters (such as 𝟚 or ᠕). If you want to match zero through nine, you must say [0-9]
.
Unfortunately, you cannot shorten that to
if ($Hour =~ /^([0-9]{2}){3}$/) { $result = "$1:$2:$3" }
because you care about all of the matches and that will only save the last one. Likewise
if ($Hour =~ /^([0-9]{6})$/) { $result = "$1:$2:$3" }
is out. You could say
($result = $Hour) =~ s/([0-9]{2})(?!$)/$1:/g;
but you would be trading clarity for a slightly shorter line.
Looks pretty good to me as it is.
You can replace each {2}
with another \d
if you want.
You could use $result=join":",$Hour=~/^(\d\d)/g
but it's not as strict - it will match any even-length string of digits at the start of a line.
I would use \z
instead of $
, unless you really want to allow an optional trailing newline character. Other than that (and the inconsistent capitalization of variables), it's fine.
Looks good. Matching a time can be taken to various level of strictness.
The above would allow for something like 999999
Another approach to match a 24-hour clock is to use
([01]?[4-9]|[012]?[0-3])
for the hour-part and then
[0-5][0-9]
for minutes.
or (for the fun of it), the hour-part can also be matched using
([01]?[0-9]|2[0-3])
精彩评论