Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
509 views
in Technique[技术] by (71.8m points)

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

opendir(DIR,"$pwd") or die "Cannot open $pwd
";
    my @files = readdir(DIR);
    closedir(DIR);
    foreach my $file (@files) {
        next if ($file !~ /.txt$/i);
        my $mtime = (stat($file))[9];
        print $mtime;
        print "
";
    }

Basically I want to note the timestamp of all the txt files in a directory. If there is a subdirectory I want to include files in that subdirectory too.

Can someone help me in modifying the above code so that it includes subdirectories too.

if i am using the code below in windows iam getting timestamps of all files which are in folders even outside my folder

 my @dirs = ("C:\Users\peter\Desktop\folder");
    my %seen;
    while (my $pwd = shift @dirs) {
            opendir(DIR,"$pwd") or die "Cannot open $pwd
";
            my @files = readdir(DIR);
            closedir(DIR);
            #print @files;
            foreach my $file (@files) {
                    if (-d $file and !$seen{$file}) {
                            $seen{$file} = 1;
                            push @dirs, "$pwd/$file";
                    }
                    next if ($file !~ /.txt$/i);
                    my $mtime = (stat("$pwd$file"))[9];
                    print "$pwd $file $mtime";
                    print "
";
            }
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
";
  }
}, '.');

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...