in reply to Re: how to list the files in dir with respect to time
in thread how to list the files in dir with respect to time

The List::Util stuff is definitely cool, but I don't quite understand why you say it reduces the number of stat calls. I would have thought that you need to stat every candidate file just once, whether you use List::Util 'reduce' or something like the more mundane hash:
my %file_date; for ( glob '/path/to/*.log' ) { $file_date{$_} = (stat)[9]; } my $newest = ( sort { $file_date{$b} <=> $file_date{$a} } keys %file_a +ge )[0];

(update: changed name of hash to be consistent with what it stores)

Replies are listed 'Best First'.
Re^3: how to list the files in dir with respect to time
by Zaxo (Archbishop) on Aug 02, 2005 at 03:36 UTC

    The map reduces the number of stat calls by half. Compare to:

    use List::Util 'reduce'; my $newest = reduce { (stat $a)[9] < (stat $b)[9] ? $b : $a } glob '/path/to/*.log';

    It's not possible to use the *_ handle for a cached stat call there, because we don't know that the currently reduced name was the subject of the most recent stat call.

    Your hash approach is fine, too, but it would also benefit from reduce() over sort.

    After Compline,
    Zaxo

Re^3: how to list the files in dir with respect to time
by sk (Curate) on Aug 02, 2005 at 03:40 UTC
    Thanks zaxo! You beat me to the punch :)

    I was confused too why zaxo said it will reduce number of stat calls. I am yet to familiarize myself with ST so i will read up on that before I ask any questions regarding that :)

    Seems like the OP wanted the last modified file. So why store all file and then sort instead of a simple max?

    Modifying graff's code here

    Update : Added logic to update $max. Thanks graff. my oversight.

    my %file_date; my $max = -99999999; # set it to first file's mtime would be better # but just for demonstration here my $mtime; my $file; for ( glob '/path/to/*.log' ) { $mtime = (stat)[9]; if ($max <= $mtime) { $file = $_; $max = $mtime; } print ("file = $file\n"); # my $newest = ( sort { $file_date{$b} <=> $file_date{$a} } keys %file +_age )[0];
      Good point about just keeping the most recent file seen so far. But you need to make sure that you update $max each time you reset the value of $file.
        duh!

        Silly me :$

        I shouldn't type code directly on the browser :)