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

I'm opening up every file in a folder for data analysis. It seems like Perl is opening up the files in alphabetical order. I'd like to have perl open up the directory in order of date created.
Is there a parameter that I can use to load the files in date order, or is there a sort mechanism that can move the file names around within my allfiles array?
$datapath = "/Users/code/data"; my @allfiles = <$datapath/*.*>; foreach $item (@allfiles) { parsing... }

Many Thanks

Replies are listed 'Best First'.
Re: Open files by date created
by davorg (Chancellor) on Sep 15, 2004 at 08:02 UTC

    Use sort...

    $datapath = "/Users/code/data"; my @allfiles = sort { -M $a <=> -M $b } <$datapath/*.*>; foreach $item (@allfiles) { # parsing... }

    Actually, as I dislike unnecessary variables, I'd probably write it as:

    $datapath = "/Users/code/data"; foreach (sort { -M $a <=> -M $b } <$datapath/*.*>) { # filename is in $_ }
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Open files by date created
by Zaxo (Archbishop) on Sep 15, 2004 at 08:19 UTC

    Here's a ST sort with a filter for regular files which doesn't depend on the presence of a dot (or its absence in directory names).

    my @files_by_mtime = map { $_->[1] } sort { $a->[0] <=> $b->[0] } map { -f ? [(stat _ )[9], $_] : () } glob "$datapath/*";

    I've substituted mtime for "creation time". The special filehandle _ avoids calling stat twice in that map block.

    After Compline,
    Zaxo

Re: Open files by date created
by eyepopslikeamosquito (Archbishop) on Sep 15, 2004 at 08:15 UTC
    davorg gave an excellent, simple and clear answer. If you are further interested in more advanced Perl sorting techniques, they were discussed at length a while back in this very similar node: Sorting based on filesize..
Re: Open files by date created
by dave_the_m (Monsignor) on Sep 15, 2004 at 10:31 UTC
    Note also that many operating systems (eg UNIX), do not record the creation time of a file, and so it's impossible to sort by creation time.

    Dave.