M.Joe M.Joe - 1 year ago 54
Perl Question

No output when using File::Find module

I would like to count the total number of files whose

is between
. Here is part of my code, but it doesn't return anything. What is wrong?

sub mtime_between {
my $mtime=0;
my $counts=0;
$mtime = (stat $File::Find::name)[9] if -f $File::Find::name;
if ($mtime > $atime and $mtime < $btime) {
return sub { print ++$counts,"$File::Find::name\n"};

When i call the subroutine, I get nothing.


Answer Source

You should not be returning a function.

Check File::Find documentation.

find() does a depth-first search over the given @directories in the order they are given. For each file or directory found, it calls the &wanted subroutine.

In the wanted function you should do the things you want to do directly. To return a function reference will not work and this is why you are having problems.

So you actually want something more like:

#!/usr/bin/env perl

use strict;
use warnings;
use feature qw{say};
use File::Find;
use Data::Dumper;

my ($atime, $btime) = (1461220840, 1561220844);

sub findFilesEditedBetweenTimestamps {
    my ($atime, $btime, $path) = @_;
    my $count = 0;
    my @files = ();

    my $mtime_between = sub {
        my $mtime = 0;
        $mtime = (stat $File::Find::name)[9] if -f $File::Find::name;
        if ($mtime > $atime and $mtime < $btime) {
            push @files, $File::Find::name;

    find ($mtime_between, $path);

    say "Found a total of $count files";
    say "Files:";
    print Dumper(@files);

findFilesEditedBetweenTimestamps($atime, $btime, "./");

I get:

Found a total of 2 files
$VAR1 = './test.txt';
$VAR2 = './test.pl';