我有一系列日期
@dates = qw(2/1/1989 2/1/1970 2/1/1970 2/1/1989 6/1/1970 12/1/1970);
我需要将它从最旧到最新排序,并在排序后返回未排序数组的索引。
输出应该是这样的
#sorted array
2/1/1970
2/1/1970
6/1/1970
12/1/1970
2/1/1989
2/1/1989
#indexes
1 2 4 5 0 3
答案 0 :(得分:1)
my @dates = qw(2/1/1989 2/1/1970 2/1/1970 2/1/1989 6/1/1970 12/1/1970);
my @idx = map $_->[0],
sort {
# compare years
$a->[3] <=> $b->[3] ||
# compare months
$a->[1] <=> $b->[1] ||
# compare days
$a->[2] <=> $b->[2] ||
# compare index for stable sort for duplicate values
$a->[0] <=> $b->[0]
}
map [$_, split /\D/, $dates[$_] ],
0 .. $#dates;
print "indexes @idx\n";
# sorted values
print "$_\n" for @dates[@idx];
输出
indexes 1 2 4 5 0 3
2/1/1970
2/1/1970
6/1/1970
12/1/1970
2/1/1989
2/1/1989
答案 1 :(得分:1)
使用Time::Piece
和Schwartzian Transform
use strict;
use warnings;
use Time::Piece;
my @dates = qw(2/1/1989 2/1/1970 2/1/1970 2/1/1989 6/1/1970 12/1/1970);
my @idx = map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [$_, Time::Piece->strptime($dates[$_], '%m/%d/%Y') ] }
(0..$#dates);
print "Indexes: @idx\n";
print "Dates: @dates[@idx]\n";
输出:
Indexes: 1 2 4 5 0 3
Dates: 2/1/1970 2/1/1970 6/1/1970 12/1/1970 2/1/1989 2/1/1989
也可以执行以下操作:
my @idx = sort {
Time::Piece->strptime($dates[$a], '%m/%d/%Y') <=> Time::Piece->strptime($dates[$b], '%m/%d/%Y')
} (0..$#dates);