Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Sorting

6 views
Skip to first unread message

ExecMan

unread,
May 12, 2012, 6:54:22 PM5/12/12
to
Hi,

I'm looking to read a directory to get a list of files in Descending
sorted order by timestamp. I've gotten this so far, but it is in
ascending. Can anyone help with the descending part?

my $dir = '/home/logfiles';

opendir my $DH, $dir or die "Cannot opendir '$dir' $!";

my @sorted_files =
map $_->[1],
sort { $a->[0] <=> $b->[0] }
map -f "$dir/$_" ? [ ( stat _ )[9], $_ ] : (),
readdir $DH;

for ($i=0; $i<20; $i++) {
print "FILE: $sorted_files[$i]\n";
}


Thank a bunch!

ntua

unread,
May 14, 2012, 6:18:54 PM5/14/12
to
sort { $b->[0] <=> $a->[0] }

Tim McDaniel

unread,
May 14, 2012, 6:41:32 PM5/14/12
to
In article
<a53b9973-46f0-482a...@w13g2000vbc.googlegroups.com>,
ExecMan <artm...@yahoo.com> wrote:
>I'm looking to read a directory to get a list of files in Descending
>sorted order by timestamp.

In Linux or other UNIX-like systems, you can use the command "ls -t".

--
Tim McDaniel, tm...@panix.com

Ben Morrow

unread,
May 14, 2012, 6:34:33 PM5/14/12
to

Quoth ExecMan <artm...@yahoo.com>:
>
> I'm looking to read a directory to get a list of files in Descending
> sorted order by timestamp. I've gotten this so far, but it is in
> ascending. Can anyone help with the descending part?
>
> my $dir = '/home/logfiles';
>
> opendir my $DH, $dir or die "Cannot opendir '$dir' $!";
>
> my @sorted_files =
> map $_->[1],
> sort { $a->[0] <=> $b->[0] }

Do you understand what this line does? In particular, what does <=>
return when

- $a->[0] is less than $b->[0]?
- $a->[0] is greater than $b->[0]?
- $a->[0] is equal to $b->[0]?

You just need to arrange for these to come out the other way around.

> map -f "$dir/$_" ? [ ( stat _ )[9], $_ ] : (),
> readdir $DH;

Ben

Jürgen Exner

unread,
May 14, 2012, 7:15:25 PM5/14/12
to
ExecMan <artm...@yahoo.com> wrote:
>I'm looking to read a directory to get a list of files in Descending
>sorted order by timestamp. I've gotten this so far, but it is in
>ascending. Can anyone help with the descending part?

If nothing else this hack will work:
perldoc -f reverse

:-)

jue

Ben Morrow

unread,
May 14, 2012, 7:54:27 PM5/14/12
to

Quoth Jürgen Exner <jurg...@hotmail.com>:
Annoyingly, while C<sort { $b <=> $a }> is optimized into a 'DESC' flag
on the sort op, C<reverse sort> is not. If it were it wouldn't be a
hack, be a good way of clearly expressing what you mean. (This is
especially annoying given that, AFAICS, the logic is there in pp_sort to
support the DESC flag with an arbitrary sort function, it just isn't
used.)

Even as it is, 'reverse' is pretty cheap: it doesn't allocate any
memory, it just reverses the list by shifting pointers around on the
stack (one pass through half the list), so it's not a bad way to sort
backwards if reversing the sense of the condition is non-trivial.

Ben

0 new messages