in reply to Sort directories by date

As RichardK wrote above:

"...It would have been much easier if you'd created the directory names as 'YYYYMMDD' then they would have sorted naturally with little effort...."

But i guess that it is like it is: You can't change that any more.

Here is another idea how to sort these directories that doesn't require any dark klingone maneuvers ;-)

#!/usr/bin/env perl use strict; use warnings; use feature qw (say); my @dates = qw{ 12112014 01052015 02202015 03102015 01012011 04092015 09092015 }; my %hash; for (@dates) { my ( $m, $d, $y ) = unpack q(a2a2a4); $hash{qq($y$m$d)} = $_; } for ( sort { $a <=> $b } keys(%hash) ) { say $hash{$_}; } __END__ karls-mac-mini:monks karl$ ./dirs.pl 01012011 12112014 01052015 02202015 03102015 04092015 09092015

Please see also Path::Iterator::Rule, File::Basename, unpack, pack as well as perlpacktut.

Regards, Karl

«The Crux of the Biscuit is the Apostrophe»

Replies are listed 'Best First'.
Re^2: Sort directories by date
by Laurent_R (Canon) on Sep 29, 2015 at 20:44 UTC
    Yeah, but why would you want to populate a hash and use sort, when you already have everything at hand and only need one very small extra step to find the max value?
    #!/usr/bin/env perl use strict; use warnings; use feature qw (say); my @dates = qw{ 12112014 01052015 02202015 03102015 01012011 04092015 09092015 }; my $max_date = 0; my $result; for (@dates) { my $date = join "", reverse unpack q(a4a4); $result = $_ and $max_date = $date if $date > $max_date; } print $result;
    Update: fixed a mistake (missing reverse) in the my $date = ... code line above. Thanks to poj for pointing out the error.
      "...why would you want to populate a hash and use sort..."

      Because i had no better idea :-(

      Update: No, wait:

      use strict; use warnings; use feature qw (say); use List::Util qw(max); use Time::Piece; my @dates = qw{ 12112014 01052015 02202015 03102015 01012011 04092015 09092015 }; say localtime( max map { Time::Piece->strptime( $_, "%m%d%Y" )->epoch +} @dates ) ->strftime("%m%d%Y"); __END__ \Desktop\monks>other_idea.pl 09092015

      Best regards, Karl

      «The Crux of the Biscuit is the Apostrophe»