The only other way I can think of (others may know better) would be to parse the output from ls or dir with the appropriate sort options. but that is much harder than using a hash to control a sort.

#! perl -sw use strict; my %times; opendir DIR, $ARGV[0] or die "Couldn't open $ARGV[0]; $!\n"; my @sorted = sort { $times{$b} <=> $times{$a}; # Was cmp D'oh! Thanks [dws] } map { $times{$_} = (stat $_)[9]; $_; } grep{ -f $_ } readdir DIR; closedir DIR or warn "Couldn't close $ARGV[0]; $!\n"; local $" = $/; print "@sorted\n";

You might need to change the stat index from 9 to either 8 or 10 depending upon your needs.

I also think that testing using -f is safer than using your match to rid yourself of '.' and '..', though if your on a system that supports and uses symbolic links for example, you might need to bolster the grep test.

Oh! And if you want them oldest first, switch the order of $a and $b of course.

Updated to correct cmp -v- <=> error. Thanks dws.


Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!

In reply to Re: READDIR - Sort by Time? by BrowserUk
in thread READDIR - Sort by Time? 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.