2014-05-23 106 views
-1

返回指數我有日期日期排序的陣列和在Perl

@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 
+2

歡迎#1。你試過什麼了? – KeepCalmAndCarryOn

+0

這些國際日期,還是北美? – Borodin

回答

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

使用Time::PieceSchwartzian 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);