in reply to sorting a directories content

print join "\n", sort @DirList;

prints sorted by file/dir name.

print join "\n", sort {-M $a <=> -M $b} @DirList;

prints sorted by modification date.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: sorting a directories content
by betterworld (Curate) on Apr 13, 2007 at 13:25 UTC
    print join "\n", sort {-M $a <=> -M $b} @DirList;

    This will result in a flood of stat calls. This would be more efficient:

    print join "\n", map $_->[0], sort {$a->[1] <=> $b->[1]} map [$_, -M], @DirList;

    Plus, one might want to do something if -M returns undef (due to permission problems or broken symlinks).

    Update: corrected my silly typing errors, thanks to GrandFather

      The Schwartzian Transform is indeed most appropriate in this case. However your sort code is a little buggy. OP may have better luck with:

      print join "\n", map {"$_->[0]"} sort {$a->[1] <=> $b->[1]} map {[$_, +-M]} @DirList;

      Note that the replies to What is "Schwarzian Transform" (aka Schwartzian) contain many useful comments and references pertaining to the Schwartzian Transform too.


      DWIM is Perl's answer to Gödel

        An even faster solution that sorts files with identical timestamps by name:

        # Assumes 32-bit timestamps. print map { substr($_, 4) . "\n" } sort map { pack('Na*', (stat($_))[9], $_) } @DirList;
A reply falls below the community's threshold of quality. You may see it by logging in.