我有一个像这样的数组@dates
:
month [
[0] "Sep 8, 12, 15, 24",
[1] "May 3, 24, 25, 29",
[2] "Jan 23",
...
]
每月只会在数组@month中包含一次,但不会按时间顺序排列。
perl是否有内置函数来尝试将字符串解释为可用于按时间顺序对此数组进行排序的日期?
答案 0 :(得分:2)
使用月索引的辅助散列
按每个字符串的前三个字符排序use warnings;
use strict;
use feature 'say';
my @data = ("Sep 8, 12, 15, 24", "May 3, 24, 25, 29", "Jan 23");
my @mons = qw(jan feb mar apr may jun jul aug sep oct nov dec);
my %mon_ind = map { $mons[$_] => $_+1 } 0..$#mons;
my @sorted_data = sort { by_mon(\%mon_ind, $a, $b) } @data;
say for @sorted_data;
sub by_mon {
my $mi = shift;
my ($m1, $m2) = map { lc(substr $_, 0, 3) } @_;
return $mi->{$m1} <=> $mi->{$m2};
}
打印
Jan 23 May 3, 24, 25, 29 Sep 8, 12, 15, 24
代码posted on pastebin有效地尝试实现排序。