我该如何在Perl中对日期进行排序?
我有一个包含以上日期的数组。如何对这些日期进行排序?
我的日期格式为
my @dates = ( "02/11/2009" , "20/12/2001" , "21/11/2010" );
我有一个包含以上日期的数组。如何对这些日期进行排序?
我的日期格式为
dd/mm/YYYY
。@dates = sort { join('', (split '/', $a)[2,1,0]) cmp join('', (split '/', $b)[2,1,0]) } @dates;
或者使用单独的排序子程序:
sub mysort {
join('', (split '/', $a)[2,1,0]) cmp join('', (split '/', $b)[2,1,0]);
}
@dates = sort mysort @dates;
更新:更高效的方法是使用Schwartzian Transform:
@dates =
map $_->[0],
sort { $a->[1] cmp $b->[1] }
map [ $_, join('', (split '/', $_)[2,1,0]) ], @dates;
sort { join('', (split '[\/\-]', $a)[2,1,0,3]) cmp join('', (split '[\/\-]', $b)[2,1,0,3]) }
。 - gaoithe基于这个原因,我更喜欢YYYY/MM/DD
的日期格式。它可以确保在1000/01/01
和9999/12/31
之间正确排序。
my @sorted_alt = sort map { join '/', reverse split '/', $_ } @dates;
DD/MM/YYYY
格式显示日期,你可以尝试使用完整的Schwartzian transform。my @sorted = map {
join '/', reverse split '/', $_
}
sort
map {
join '/', reverse split '/', $_
} @dates;
或者
my @sorted = map {
join '/', reverse @$_
}
sort { "@$a" cmp "@$b" }
map {
[ reverse split '/', $_ ]
} @dates;
这里有很多人正确地认为日期的原始格式应该是yyyy-mm-dd格式,但是还没有人给出可以处理这种情况的Perl代码。所以在这里提供一下:
my @dates = (
'2014-08-15',
'2016-09-13',
'2001-01-02',
'1998-09-22',
'1998-09-21',
'1998-09-23',
'1999-04-20',
'2020-01-30',
);
@dates = sort {$a cmp $b} @dates; # 1998 is the first date's year
@dates = sort {$b cmp $a} @dates; # 2014 is the first date's year
@dates = sort @dates;
。 - melpomene或者使用时间戳的纪元格式并将它们作为数字进行排序。然后按照您想要的输出格式转换日期字符串。这样,您就不必被原始字符串的格式束缚住。