Home > Software design >  What is the simplest way to find files modified within the past hour?
What is the simplest way to find files modified within the past hour?

Time:12-16

This question is a special case of "in perl, what is the simplest way to find files modified within a given time interval?" and the solution below could easily be generalized. In bash, we can type

> find . -mtime -1h

but I want to do this in pure perl. The code below does this. It explicitly runs stat on each file.

Is there any way that this can be made simpler or more elegant? Granted, this is slower than the bash command; I am not trying to compete with bash for efficiency. I'm just trying to do it purely in perl.

#!/usr/bin/env perl 
use strict; use warnings;
use File::Find;
my $invocation_seconds=time;
my $interval_left =  $invocation_seconds - (60 * 60); # one hour ago
my $count_all=0;
my @selected;
find(
    sub
    {
        $count_all  ;
        my $mtime_seconds=(stat($_))[9];
        return unless defined $mtime_seconds; # if we edit files while running current script, this can be undef on occasion 
        return unless ($mtime_seconds>$interval_left);
        push@selected,$File::Find::name;
    }
    ,
    '.', # current directory 
);
my $end_seconds=time;
my $totalselected=scalar@selected;
print ($_,"\n",)for@selected;
print $^V; print " <- perl version\n";
print 'selected ',$totalselected, '/',$count_all,' in ',($end_seconds-$invocation_seconds),' seconds',"\n";

CodePudding user response:

use Find::File::Rule qw( );

my $cutoff = time - 60*60;

say for Find::File::Rule->mtime( ">=$cutoff" )->in( "." );

CodePudding user response:

Following demo sample code utilizes function stat to filter out files modified in last hour.

Note: with slight modification the code can be adopted for recursion

use strict;
use warnings;
use feature 'say';

use constant STAMP => time() - 60*60;
use constant MTIME => 9;

my $dir = shift || '.';
my @files;

(stat($_))[MTIME] > STAMP && push @files, $_
    for glob("$dir/*");

say "
Files changes in last hour
--------------------------";
say for @files;
  • Related