我有一系列的日期‘YYYY-月’,比如‘2013-12月’,‘2014-5月’等等。我需要在数组中找到最近日期的索引。有没有内置的模块来做这件事。
发布于 2014-05-26 05:50:56
使用Time::Piece strptime解析日期。
然后使用date comparisons确定哪一个是最新的。
use strict;
use warnings;
use Time::Piece;
use List::Util qw(reduce);
my @strings = qw(2013-Dec 2014-May 2014-Jan 2014-Feb 2014-Jan);
my @dates = map {Time::Piece->strptime($_, "%Y-%b")} @strings;
my $maxid = reduce {$dates[$b] > $dates[$a] ? $b : $a} (0..$#dates);
print "$strings[$maxid]\n"产出:
2014-May发布于 2014-05-26 06:57:21
如果您不想使用任何模块,那么使用下面的代码。
#!/usr/bin/perl
# your code goes here
use strict;
use warnings;
my @dates = ( '2013-Dec', '2014-May', '1992-July', '2014-Jan' );
my @sorted_dates = sort { (split /\-/, $a)[0] <=> (split /\-/, $b)[0] ||
(split /\-/, $a)[1] cmp (split /\-/, $b)[1]
} @dates;
print "Latest date is ".$sorted_dates[-1]. " index is $#sorted_dates";Demo
https://stackoverflow.com/questions/23863469
复制相似问题