簡體   English   中英

如何使用Perl在目錄及其所有子目錄中找到最新的.pl文件?

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

如何掃描整個目錄的內容,包括其子目錄的內容,並使用Perl查找其中的最新.pl文件?

我想在目錄樹中構建所有.pl文件的完整文件路徑的排序數組/列表。

因此,例如,如果我的基本目錄是/home/users/cheeseconqueso/我想搜索該目錄中的.pl文件以及該路徑中的任何子目錄,然后按日期對.pl文件進行排序。

最終的結果是一個數組@pl_paths ,其中$pl_paths[0]類似於/home/users/cheeseconqueso/maybe_not_newest_directory/surely_newest_file.pl

從那個結果來看,我想執行該文件,但是我認為一旦我得到排序的數組,在$pl_paths[0]執行該文件,就不會有問題了。

有一個類似的問題,我一直試圖修改,以滿足我的需要,但我現在在這里顯而易見的原因。

我用來在一個目錄中獲取最新文件NAME的代碼是:

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);
print $sorted_files[0]."\n";

如果你想要一個核心模塊,你可以使用File :: Find ,但我更喜歡使用File :: Find :: Rule

首先,我們可以在目錄下找到所有.pl文件

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

然后讓我們使用map將文件名與其修改時間相關聯:

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

並按mtime排序:

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

從那里,最新的名稱是$sorted_files[0]{name}

如果你只想找到最上面的那個,實際上沒有必要做一個完整的排序,但我能想到的最好的解決方案涉及一些稍微高級的FP,所以如果它看起來很奇怪你不要擔心它:

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

使用File :: Find :: RuleSchwartzian變換 ,您可以在從dir_path開始的子樹中獲得帶有.pl擴展名的最新文件。

#!/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 ];

map-sort-map鏈是一個典型的習慣用法:獲取時間戳很慢,所以我們每個文件只執行一次,將每個時間戳與其文件保存在arrayref中。 然后我們使用時間戳(比較每個arrayref的第二個元素)對新列表進行排序,最后我們丟棄時間戳,只保留文件名。

使用File :: Find核心模塊。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM