Believe it or not, your question may actually be ambiguous. The "latest" directory could either be the one whose name represents the most recent month-day-year date, OR the one whose modification date is the most recent (i.e. the one that has most recently had a file added, deleted, renamed, etc.). The other replies above all take it for granted that the first of these two was your intended meaning.

But maybe those two possible interpretations happen to yield the same relative ordering of directories - that is, it could be that no changes ever occur in the contents of "09302015" once "10012015" is created (and likewise for the latter, once "10022015" is created). If this is true, you can sort the directories based on their modification dates:

my $dir = "/my_dir"; opendir DIR, $dir or die "$dir: $!\n"; my %subdir; while ( my $month_dir = readdir( DIR ) { next unless ( $month_dir =~ /^\d{8}$/ ); $subdir{$month_dir} = -M $month_dir; } my $latest_dir = ( sort {$subdir{$a}<=>$subdir{$b}} keys %subdir )[0]; # ...
Of course, if you really, truly meant for the actual directory names to be the basis for sorting, then the Schwartzian Transform is probably the most economical: instead of using the hash and while loop shown above, just do this:
my $latest_dir = ( map{s/(....)(....)/$2$1/; $_} sort map{s/(....)(....)/$2$1/; $_} grep /^\d{8}$/, readdir DIR )[-1];

In reply to Re: Sort directories by date by graff
in thread Sort directories by date by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.