DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Sort File List By Month Name In Perl

11.06.2009
| 4123 views |
  • submit to reddit
        Sort a list of files by the month name

#!/usr/bin/perl -w
#
#
#
use strict;

my @mon = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my $mon;
@{$mon}{@mon} = (0..$#mon);

my $data = <<EOT;
-rw-r--r--   1 root     other         48 Nov  5 03:57 /tmp/file.txt
-rw-r--r--   1 root     other         48 Aug  8 13:12 /tmp/file.txt
EOT

my $list;

for my $line ( split(/\n/, $data) ) {

    my @ls = split(/\s+/, $line);

    $list->{$line}->{mon} = $mon->{$ls[5]};

}

sub by_month ($$) {
    my ($a, $b) = (shift, shift);
    $list->{$a}->{mon} <=> $list->{$b}->{mon};
}

for my $line ( sort by_month keys %{$list} ) {
    print "$line\n";
}