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

后端 未结 3 1986
旧时难觅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:20

    With File::Find::Rule, and Schwartzian transform, you can get the newest file with .pl extension, in a subtree starting from dir_path.

    #!/usr/bin/env perl
    
    use v5.12;
    use strict;
    use File::Find::Rule;
    
    my @files = File::Find::Rule->file()->name( '*.pl' )->in( 'dir_path' );
    
    # Note that (stat $_ )[ 9 ] yields last modified timestamp
    @files = 
       map { $_->[ 0 ] }
       sort { $b->[ 1 ] <=> $a->[ 1 ] }
       map { [ $_, ( stat $_ )[ 9 ] ] } @files;
    
    # Here is the newest file in path dir_path
    say $files[ 0 ];
    

    The map-sort-map chain is a typical idiom: getting timestamp is slow, so we do it only one time per file, keeping every timestamp with its file in an arrayref. Then we sort the new list using timestamp ( comparing the second element of each arrayref ), and finally we discard timestamps, keeping only filenames.

提交回复
热议问题