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.


In reply to Re: Problem in date checking script by ferreira
in thread Problem in date checking script by garyprmr

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.