M.Joe M.Joe - 2 years ago 84
Perl Question

Questions about perl closure

I would like to count number of files whose modify_time between

,here is part of my code, but it didn'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 got 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';
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download