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

Hi,

I am looking at ways to determine which is the latest log file in a directory. What I was thinking of doing was using the -M operator to find the age in days since the file was last modified, pushing the filename and timestamp into a hash and then sorting the array and poping of the first value.

I'm still a bit of a novice here but is there an easier way of doing this?

Cheers

./stew

Replies are listed 'Best First'.
Re: Assesing file timestamp
by broquaint (Abbot) on Jan 30, 2003 at 13:38 UTC
    Should be able to do it in a single line ...
    print +(sort { $a->[1] <=> $b->[1] } map [$_, -M], <*.log>)[0]->[0];
    There you're globbing on *.log, creating a list of anonymous arrays containing filename and timestamp, sorting on timestamp then getting the first element out of the sorted list and dereferencing the first element (which of course will contain the filename).
    HTH

    _________
    broquaint

Re: Assesing file timestamp
by davorg (Chancellor) on Jan 30, 2003 at 13:37 UTC
    my $latest = (sort { -M $a <=> -M $b } </path/to/dir/*.log>)[0];
    --
    <http://www.dave.org.uk>

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

      Isn't that horribly inefficient to stat a file multiple times in the sort? Wouldn't this be the perfect place for a Schwartzian transform (as employed by broquaint) or an 'orcish' maneuver?

      Or am I missing some internal caching going on here?

      Update: Got a bit carried away there with my adverb ... I just wanted to make sure that I hadn't missed anything. Thanks for the clarification, davorg.

      -- Hofmator

        Well, I don't know about "horribly inefficient", but it's certainly not the fastest way to do it. broquaint's solution would be faster.

        --
        <http://www.dave.org.uk>

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

Re: Assesing file timestamp
by physi (Friar) on Jan 30, 2003 at 13:47 UTC
    Try:
    opendir DIR, "/path/to/logdir/"; my @files = readdir DIR; closedir DIR; my $latest; for $file (@files) { next if $file =~ /^\.+/; $latest = (stat($file))[9] > (stat($latest))[9] ? $file : $latest; } print "Last Logfile: $latest\n";