Let's say that for some reason you wanted something different than just an ASCII sort, in this case you lucked out because a simple sort works. But let's say maybe there weren't leading zero's (that makes an ASCII date sort possible!), and say you for some reason wanted sort order, to be month, reverse day, reverse time, here is how that could be accomplished...
The sort function can take a subroutine that you supply! That subroutine produces -1,0,1 depending upon how you figure things should be compared. $a and $b are "magic variables" and will "just be there as part of the sort". The basic procedure is to take the $a and $b variables, use split or regex to break them apart into the things that are relevant for your tricky sort. Then compare them as you wish. My example above shows how I do this with the code layout that I prefer (a clear "stack" of comparisons). For numeric compare, use the "spaceship" operator <=>, for string compare use "cmp". Here I used numeric compares. Notice that what happen in the regex's in sort{} didn't affect the result (they are still just ascii). The list that comes into the sort is what comes out of the sort. You are just supplying a function that compares the lines as the sort routine requests. Note to reverse the order I just swapped the "a" version and the "b" version in the compare functions.#!/usr/bin/perl use strict; use warnings; my @dates = ( '01-30 22:10', '01-12 05:56', '01-24 01:42', '01-12 05:59', '01-31 01:33', '01-02 01:33', ); @dates = sort @dates; for (@dates) { print $_, "\n"; } #prints: #01-02 01:33 #01-12 05:56 #01-12 05:59 #01-24 01:42 #01-30 22:10 #01-31 01:33 print "\n"; @dates = sort { my ($amonth,$aday,$ahour,$amin) = $a =~/(\d+)-(\d+)\s+(\d+):(\d+)/; my ($bmonth,$bday,$bhour,$bmin) = $b =~/(\d+)-(\d+)\s+(\d+):(\d+)/; $amonth <=> $bmonth or $bday <=> $aday or $bhour <=> $ahour or $bmin <=> $amin }@dates; for (@dates) { print $_, "\n"; } #prints: #01-31 01:33 #01-30 22:10 #01-24 01:42 #01-12 05:59 #01-12 05:56 #01-02 01:33
There are ways to make this computationally more efficient but that requires building lists of anonymous lists (basically do all the splitting,regexing at once instead of doing it each time for the $a and $b variables). Master this type of sorting first.
Hope this gives an idea of how to solve more complex problems and happy sorting! Perl is great at it!
In reply to Re^3: Sort by Date and Time
by Marshall
in thread Sort by Date and Time
by zod
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |