How to traverse all the files in a directory; if it has subdirectories, I want to traverse files in subdirectories too

File::Find is best for this. It is a core module so doesn't need installing. This code does the equivalent of what you seem to have in mind

use strict;
use warnings;

use File::Find;

find(sub {
  if (-f and /\.txt$/) {
    my $mtime = (stat _)[9];
    print "$mtime\n";
  }
}, '.');

where '.' is the root of the directory tree to be scanned; you could use $pwd here if you wish. Within the subroutine, Perl has done a chdir to the directory where it found the file, $_ is set to the filename, and $File::Find::name is set to the full-qualified filename including the path.


use warnings;
use strict;

my @dirs = (".");
my %seen;
while (my $pwd = shift @dirs) {
        opendir(DIR,"$pwd") or die "Cannot open $pwd\n";
        my @files = readdir(DIR);
        closedir(DIR);
        foreach my $file (@files) {
                next if $file =~ /^\.\.?$/;
                my $path = "$pwd/$file";
                if (-d $path) {
                        next if $seen{$path};
                        $seen{$path} = 1;
                        push @dirs, $path;
                }
                next if ($path !~ /\.txt$/i);
                my $mtime = (stat($path))[9];
                print "$path $mtime\n";
        }
}

use File::Find::Rule

File::Find::Rule is a friendlier interface to File::Find. It allows you to build rules which specify the desired files and directories.