在我的程序中,我让用户以"Month Day"的格式输入日期(例如5月25日),如果它是无效日期(例如2月30日),我希望能够打印错误消息。
这里有一些代码
$start_date = ARGV[0];
my $year = DateTime->now->year; # adds a year to the date
my $date_parser = DateTime::Format::Strptime->new(pattern => '%Y %B %d', # YYYY Month DD
);
my $start_epoch = $date_parser->parse_datetime("$year $start_date")->epoch();
在这之后,我需要一些if语句?
如果日期无效,那么解析器将返回undef
。如果这样做,您将很快看到:
my $start_date = "Feb 30";
my $year = DateTime->now->year; # adds a year to the date
my $date_parser = DateTime::Format::Strptime->new(pattern => '%Y %B %d', # YYYY Month DD
);
my $start_epoch = $date_parser->parse_datetime("$year $start_date")->epoch();
解决方案:
my $parsed = $date_parser->parse_datetime("$year $start_date");
if ( not defined $parsed ) { print "Error - invalid daten"; }
From perlmonks:
use Time::Local; my $date = ' 19990230'; # 30th Feb 1999 $date =~ s/s+$//; $date =~ s/^s*//; my ($year, $month, $day) = unpack "A4 A2 A2", $date; eval{ timelocal(0,0,0,$day, $month-1, $year); # dies in case of bad date + 1; } or print "Bad date: $@";
这对你来说应该是公平的