Perl:查找超过X分钟的文件的最快方法,从最旧到最新排序

时间:2017-07-16 16:11:33

标签: perl file sorting find

我试图检查是否有一个比X minuts更早的文件(我不关心文件夹)。不幸的是,我可以告诉我这个代码的错误在哪里。 我会批评任何帮助:)

1。找到早于X分钟的文件

#!/usr/bin/perl 

my $maindir = "C:\\Users\\Dor\\Desktop\\aba";
my $minutesold = 60;
my $now = time;
my $filedisc;

# Declare arrays
my @xmlfiles;
my @qulfiedfiles; 

# Declare a Dictionary
my %filedisc;

opendir(my $dh, $maindir) or die "opendir($maindir): $!";

 # Read all the files
 while (my $de = readdir($dh)) 
 {
    # get the Full path of the file
    my $f = $maindir . $de;

    if ( -f $f )
    {

        push (@xmlfiles, $f); 

    }
}
    closedir($dh);


 # For every file in directory
 for my $file (@xmlfiles) {

    # Get stats about a file
    my @stats = stat($file);

    # If time stamp is older than minutes provided
    if ($stats[9] >= ($now - (( $minutesold * 60) ))){

       # Put the File and Time stamp in the dictionary
       print($stats[9] ."          .|           "  .$file ."\n\n");

    }

    #print($now ."\n")
    #print($now - ( $minutesold * 60) ."\n"); 
 }

4 个答案:

答案 0 :(得分:4)

通常最好使用glob而不是opendir / readdir,以避免为每个结果“重建”文件的完整路径

您可能希望在Windows上启用:bsd_glob选项,以便正确处理包含空格的路径,例如C:\Program Files

use strict;
use warnings 'all';

use File::Glob ':bsd_glob'; # Provide for spaces in path

my $root       = 'C:\Users\Dor\Desktop\aba';
my $minutesold = 60;

my @old_files = grep { -f and -M * 24 * 60 > $minutes_old } glob "$root\\*.*";

答案 1 :(得分:1)

路径和文件不正确。

my $f = $maindir . $de;

应该是(在路径和文件之间添加斜杠)

my $f = "$maindir/$de";

答案 2 :(得分:0)

解决这种功能性编程风格是我想到的方式:

my $dir = shift() || $ENV{HOME}; #command line arg or else home dir
my $minutesold = 60; #1h                                                                                                                                                                                            
opendir my $dh, $dir or die "ERR: opendir($dir) $!\n";

print
map     "$$_{timestamp}          .|            $$_{file}\n",
#sort   { $$a{timestamp} <=> $$b{timestamp} }  # sort by age
#sort   { $$a{file}      cmp $$b{file}      }  # sort by name
grep    $^T-$$_{timestamp} >= 60*$minutesold,  # $^T is program startup time()
map     {{timestamp=>(stat($_))[9], file=>$_}}
grep    -f $_,
map     "$dir/$_",
readdir $dh;

closedir $dh;

答案 3 :(得分:-1)

你错过了一种简单的方法来获取perl文件的修改时间:-M switch。

Timeline timeline = new Timeline(new KeyFrame(
    Duration.millis(1000),
    ae -> doSkellyTurn()),
    new KeyFrame(
    Duration.millis(1000 + 1000), // as mentioned by fabien, the time offset is relative to the 'start()' method, not to its previous keyframe!
    ae -> endSkellyTurn()));
timeline.play();

就这么简单。

请参阅perldoc -f -X以了解所有文件测试。