Very new to Perl and have a problem with date validation
I have the following sub running to check that user date input conforms to YYYY-MM-DD
sub validateDate {
VALIDATE-DATE: {
$date = <STDIN>;
if ($date !~
/^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/) {
print " $userStart in incorrect format, should be yyyy-mm-dd\n"
print " Would you like to re-enter a date press (Y or N)?\n";
my $choice = <STDIN>;
if ($choice =~ /[Yy]/) {
redo VALIDATE_DATE;
} else {
exit;
}
}
return $date;
}
}
However , when I run it I get this error:
Unmatched [ in regex; marked by <-- HERE in m/^(19|20)\d\d([ <-- HERE - / at common_subs.pl line 60.
Compilation failed in require at add.pl line 7.
Error says that there is an unmatched ' [ ' but this isn't the case. I assume its something wrong with the regexp itself ? I am calling the sub from a separate file.
First, escape /. / is used as delimiter for regular expression literal. / inside that literal should be escaped.
/^(19|20)\d\d([- \/.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$/
# ^^
or use different delimiter:
m{^(19|20)\d\d([- /.])(0[1-9]|1[012])\2(0[1-9]|[12][0-9]|3[01])$}
The following line is missing terminating ;:
print " $userStart in incorrect format, should be yyyy-mm-dd\n";
# ^
In fact your regex indeed is missing a ].
Since / is the delimiter symbol, the perl compiler stops at the unescaped slash inside your regex, so that you regex effectively looks like this:
/^(19|20)\d\d([- /
which obviously is missing the ] ;-)
Either use a different delimiter symbol (often people use ! or something similar) or simply escape the slash.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With