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

后端 未结 6 2341
情书的邮戳
情书的邮戳 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:45

    You don't need to keep all of the modification times and filenames in a list, and you probably shouldn't. All you need to do is look at one file and see if it's older than the oldest you've previously seen:

    {
        opendir my $dh, $dir or die "Could not open $dir: $!";
    
        my( $newest_name, $newest_time ) = ( undef, 2**31 -1 );
    
        while( defined( my $file = readdir( $dh ) ) ) {
            my $path = File::Spec->catfile( $dir, $file );
            next if -d $path; # skip directories, or anything else you like
            ( $newest_name, $newest_time ) = ( $file, -M _ ) if( -M $path < $newest_time );
        }
    
        print "Newest file is $newest_name\n";
    }
    

提交回复
热议问题