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

I would like to be able to retrieve a list of the newest N folders inside a directory and have this written to an array. Is there any way to efficiently do this without having to use the opendir() function?

Replies are listed 'Best First'.
Re: Get newest folders inside directory
by BrowserUk (Patriarch) on Nov 09, 2010 at 23:28 UTC
    @newest = (sort{ -M $a <=> -M $b } grep -d, glob '*' )[0..19];;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Thanks for your reply. Where would I specify the root folder I want to check?

        In the quotes before the '*'. If you're on win, you might want to include a drive specifier in there also: glob 'c:/*'

        @newest = (sort{ -M $a <=> -M $b } grep -d, glob '/*' )[0..19];;

        Also look at -A & -C as applicable on your OS.

Re: Get newest folders inside directory
by toolic (Bishop) on Nov 10, 2010 at 01:39 UTC
    Is there any way to efficiently do this without having to use the opendir() function?
    Building upon BrowserUk's excellent solution, here is a way to include hidden directories whose name begins with the dot character (but it still excludes the special . and .. directories). Since this uses the File::Slurp CPAN module, I doubt it is as fast as using the built-in glob function (if that's what you mean by "efficient"). You can achieve the same functionality using glob, but the code would get a little ugly (read_dir might be a little cleaner looking).
    use strict; use warnings; use File::Slurp qw(read_dir); my @newest = (sort { -M $a <=> -M $b } grep { -d } read_dir('./'))[0.. +19];

    Another subtle difference is that read_dir will die if the directory can not be opened, whereas glob will not.

    Why don't you want to use opendir?