The problem with your piece of code is that the regex you tried to build include "/" and the delimiters are also "/". This is going to work:
chomp($value = <STDIN>);
if ($value =~ m#(0[1-9]|[12][0-9]|3[01])[-/.](0[1-9]|1[012])[- /.](\d\
+d\d\d)#) {
print "date";
} else {
print $value; print "not a date";
}
Here I used alternative delimiters by using m## syntax. You may read more about it at section "Regexp Quote-Like Operators" in perlop.
And while we're at the issue of validating dates, your code may work for dates like "01/02/2007" and recognize "32/04/2007" as bad, but it will accept things like "29/02/2007" and the like. If you want correctness and minimum effort, you can use some CPAN module to check it out for you. For instance, using DateTime::Format::Strptime, you may write code like this:
se DateTime::Format::Strptime;
my $dt_format = DateTime::Format::Strptime->new(pattern => "%d-%m-%Y")
+;
sub val_date {
my $dt = shift;
$dt =~ s|[./]|-|g; # '.' and '/' become '-' for simplicity
return $dt_format->parse_datetime($dt);
}
my $s = '01-02-2007';
my $dt = val_date($s);
if ($dt) {
print "valid date\n";
} else {
print "not a date\n";
}
As an extra bonus, the return of val_date gives you a DateTime object which is much better to handle than just a string. |