How can I find the newest .pl file in a directory and all its subdirectories using Perl?

后端 未结 3 1999
旧时难觅i
旧时难觅i 2021-01-19 15:15

How can I scan an entire directory\'s contents, including its subdirectories\' contents, and find the newest .pl file within them using Perl?

I want to

3条回答
  •  忘掉有多难
    2021-01-19 16:13

    You can use File::Find if you want a core module for this, but I would prefer to use File::Find::Rule.

    To start off, we can find all of the .pl files under a directory with

    use File::Find::Rule;
    my @files = File::Find::Rule->file
                                ->name('*.pl')
                                ->in($directory);
    

    Then let's use map to associate filenames with their modification times:

    my @files_with_mtimes = map +{ name => $_, mtime => (stat $_)[9] }, @files;
    

    And sort them by mtime:

    my @sorted_files = reverse sort { $a->{mtime} <=> $b->{mtime} } 
                    @files_with_mtimes;
    

    And from there, the name of the newest one is in $sorted_files[0]{name}.

    If you only want to find the top one, there's actually no need to do a complete sort, but the nicest solution I can think of involves some slightly advanced FP, so don't worry about it at all if it looks strange to you:

    use List::Util 'reduce';
    my ($top_file) = reduce { $a->{mtime} >= $b->{mtime} ? $a : $b } 
      @files_with_mtimes;
    

提交回复
热议问题