Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

In this code:
opendir (DIR, $FirstDirToOpen) or die "Couldn't open $FirstDirToOpen: +$!\n"; my @DirList = grep (!/^\.\.?$/, readdir(DIR)); closedir(DIR);

Is there a way to sort the contents of the directory, by say newest to oldest or any other way?

Thank you much

Replies are listed 'Best First'.
Re: sorting a directories content
by GrandFather (Saint) on Apr 12, 2007 at 00:18 UTC
    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
      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
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: sorting a directories content
by grinder (Bishop) on Apr 12, 2007 at 12:33 UTC

    Side note: don't use !/^\.\.?$/ to filter out the current and parent directories. A more robust way is to use direct comparisons: $_ ne '.' and $_ ne '..'

    That way you can never be tricked by dodgy files with names like ".\n".

    • another intruder with the mooring in the heart of the Perl

      That way you can never be tricked by dodgy files with names like ".\n".

      You can replace $ with \z, that is also newline-safe.

Re: sorting a directories content
by aquarium (Curate) on Apr 12, 2007 at 00:12 UTC
    you'll need to stat each file to get the information you need (date/time stamps etc) and devise a sort routine.
    the hardest line to type correctly is: stty erase ^H