in reply to READDIR - Sort by Time?

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!

Replies are listed 'Best First'.
Re: Re: READDIR - Sort by Time?
by dws (Chancellor) on Sep 24, 2002 at 18:18 UTC
    There's an interesting failure mode embedded in
    sort { $times{$b} cmp $times{$a}; } map { $times{$_} = (stat $_)[9]; $_; }
    That you won't notice if all of your files are recent, but will cause odd results if one or more of your files predate 6:46:40pm, September 8, 2001.

    See it?

      Yes, though the 'clue' threw me for a few seconds. Thank &deity; for Date::Manip::UnixDate( '%s', 'datestring' );


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

      Though the breakpoint appears to be somewhat different?

      perl> print UnixDate( '2:46:40am, September 9, 2001.', '%s') 1000000000 perl>

      Cor! Like yer ring! ... HALO dammit! ... 'Ave it yer way! Hal-lo, Mister la-de-da. ... Like yer ring!
        Though the breakpoint appears to be somewhat different?

        Oops. It's dependent on timezone, which classifies it as a subspecies of the dread Heisenbug. You get a different result depending on where you test it.