I have several thousand objects with a string property in the format of "yyyy-MM-ddTHH:mm:ssZ"
. I want to sort 开发者_运维知识库these objects by time.
Are there any useful packages or scripts for this?
(Currently I'm just comparing individual numeric values and it seems it's not very efficient and neat.)
sort
without a sorting function sorts in lexicographical order. It fulfills your needs.
@sorted = sort @timestamps;
Timestamps in that format can be sorted lexicographically, so normal perl "sort" and the string comparison function "cmp" are sufficient.
You can use Time::Local to convert your date to timestamp or one of the Date:: modules from cpan. You can have a look at this to see what is available.
Also notice that with the above format sorting the objects lexicographicaly would also do the trick (even if probably somewhat slower than comparing numbers, but initial conversion has it's cost).
Be careful if you use dates from throughout the world because you may encounter sort problems with timezone and daylight savings. If all datetimes are in the same place that should be OK.
Provided your string format is rigid, you can use the following subroutine to sort out your list of dates.
sub timeSort {
my ($time) = ( shift =~ /\d{2}:\d{2}:\d{2}/ );
return $time;
}
my @sortedList = sort { timeSort($a) <=> timeSort($b) } @oldList;
精彩评论