views:

340

answers:

3

Related/Possible duplicate: How can I validate dates in Perl?

I have created a script where start and end date needs to be given by user while executing the script. The date format entered by user should be in YYYY-MM-DD format only.

start_date = $ARGV[0];
end_date = $ARGV[1];

please advise.

+2  A: 

First,

my ($start_date, $end_date) = @ARGV;

works too.

if ( $var =~ /^(?<year>[0-9]{4})-(?<month>[0-9]{2})-(?<day>[0-9]{2})$/ ) {
    # see %+ in perldoc perlvar

Now, you need to make sure the values are valid years, months and days.

Sinan Ünür
You should note that named captures require Perl 5.10 and (probably) provide a fallback for older versions.
Michael Carman
+1  A: 

Assuming what you mean is

$start_date = $ARGV[0];
$end_date = $ARGV[1];

i.e. syntactically valid Perl code, then you might do something like

die "Please enter dates in YYYY-MM-DD format\n"
    unless $start_date =~ /^\d{4}-\d\d-\d\d$/;
die "Please enter dates in YYYY-MM-DD format\n"
    unless $end_date =~ /^\d{4}-\d\d-\d\d$/;
chaos
+5  A: 

As noted by others, this could be done with regular expressions. However, if you want to quickly implement a complete and robust solution, then CPAN is your friend.

This TechRepublic article contains a good comparison of Date & Time modules on CPAN.

For your particular use, you should consider Time::Normalize. See the Diagnostics section of its documentation.

See also How can I validate dates in Perl? on SO.

Tim Henigan