How can I find the newest created file in a directory?

后端 未结 6 2348
情书的邮戳
情书的邮戳 2020-12-15 05:06

Is there an elegant way in Perl to find the newest file in a directory (newest by modification date)?

What I have so far is searching for the files I need, and for e

6条回答
  •  一个人的身影
    2020-12-15 05:35

    Assuming you know the $DIR you want to look in:

    opendir(my $DH, $DIR) or die "Error opening $DIR: $!";
    my %files = map { $_ => (stat("$DIR/$_"))[9] } grep(! /^\.\.?$/, readdir($DH));
    closedir($DH);
    my @sorted_files = sort { $files{$b} <=> $files{$a} } (keys %files);
    # $sorted_files[0] is the most-recently modified. If it isn't the actual
    # file-of-interest, you can iterate through @sorted_files until you find
    # the interesting file(s).
    

    The grep that wraps the readdir filters out the "." and ".." special files in a UNIX(-ish) filesystem.

提交回复
热议问题