On Thu, May 1, 2008 at 8:45 PM, Richard Lee <[EMAIL PROTECTED]> wrote:
snip
>  ls -ltr | tail -100 | cut -d' ' -f13
snip

Let's pick this apart, shall we?

ls -tr gets all of the (non-hidden) files in the current directory
reverse sorted by time (the l is unnecessary and is why you need the
cut later) and the tail takes the last one hundred (or fewer) of them.

Well, Perl can get all of the (non-hidden) files in the current
directory very easily with glob*:

my @files = <*>;

The next step is to sort them on mtime (largest mtime values last)
using stat** to get the mtime and sort*** to sort the list:

my @files = sort { (stat $a)[9] <=> (stat $b)[9] } <*>;

All of those calls to stat to get the mtime during the sort can be
expensive, so we might want to do a Schwartzian Transform**** to speed
it up:

my @files =
    map { $_->[1] }
    sort { $a->[0] <=> $b->[0] }
    map { [(stat)[9], $_] } <*>;

To get the last hundred files we can use a list slice***** using the
range operator******:

my @files = (
    map { $_->[1] }
    sort { $a->[0] <=> $b->[0] }
    map { [(stat)[9], $_] } <*>
)[-100 .. -1];

But this leaves use with undefs if we have fewer than one hundred
files in the current directory, so we need a grep******* to weed them
out:

my @files = grep defined, (
    map { $_->[1] }
    sort { $a->[0] <=> $b->[0] }
    map { [( stat)[9], $_ ] } <*>
)[-100 .. -1];

* http://perldoc.perl.org/functions/glob.html
** http://perldoc.perl.org/functions/stat.html
*** http://perldoc.perl.org/functions/sort.html
**** http://en.wikipedia.org/wiki/Schwartzian_transform
***** http://perldoc.perl.org/perldata.html#Slices
****** http://perldoc.perl.org/perlop.html#Range-Operators
******* http://perldoc.perl.org/functions/grep.html

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to