readdir

Discussion in 'Perl Misc' started by George Mpouras, Oct 29, 2013.

  1. is there any way readdir to return me files by modification time ? I do
    not want keep their dates on an array and sort it . I wantone pass like
    ls -ltr
    George Mpouras, Oct 29, 2013
    #1
    1. Advertising

  2. George Mpouras

    Guest

    On Tuesday, October 29, 2013 4:06:59 PM UTC-6, George Mpouras wrote:
    >
    > Is there any way readdir to return me files by modification time ?
    > I do not want keep their dates on an array and sort it .
    > I want one pass like
    >
    > ls -ltr



    Dear George,

    The readdir() function returns files in whatever order it wants. Well, there's more to it than that, but you need to remember that you can't assume it will ever be in any meaningful order. That's why Perl gives us the sort() function.

    You probably already know that if you want to sort filenames ASCII-betically, you can do so this way:

    @fileNames = sort @fileNames;

    Sorting by modification time is a bit more involved. Fortunately, you can use a Schwartzian Transform like this one:

    @fileNames = map {$_->[0]}
    sort {$b->[1] <=> $a->[1]}
    map {[$_, -M $_]} @fileNames;

    (It is important to remember that the entries in @fileNames must contain a proper path to each file. If the entries are just basenames (that is, theyhave no path) and the files are not in the current working directory, thenthis sort won't work properly.)

    It's just one line long (though I had to break it up to avoid line-wrapping). If it's not clear to you what it's doing, I suggest you read up on Schwartzian Transforms. If you want to stick to the perldocs, you can read about them in perlfaq4 with the command:

    perldoc -q "sort an array"

    Schwartzian Transforms can be very helpful, especially if you want to sort an array of filenames in just one pass. But they're not immediately intuitive, which is why it would be wise to study them enough to understand how to implement them in any programming language.

    I hope this helps, George.

    -- Jean-Luc
    , Nov 6, 2013
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Matt
    Replies:
    2
    Views:
    727
  2. Ramon
    Replies:
    5
    Views:
    10,755
    John C. Bollinger
    Jan 3, 2005
  3. electric sheep

    readdir() and S_ISDIR(stat.st_mode) question (OT ?)

    electric sheep, Mar 4, 2004, in forum: C Programming
    Replies:
    2
    Views:
    11,494
    Villy Kruse
    Mar 4, 2004
  4. John Stoffel
    Replies:
    0
    Views:
    146
    John Stoffel
    Feb 6, 2009
  5. ARod

    remote readdir()

    ARod, Jul 29, 2003, in forum: Perl Misc
    Replies:
    5
    Views:
    185
    programmer
    Jul 30, 2003
Loading...

Share This Page