在文件夹和子文件夹中查找文件

Find files in the folder and subfolder

我正在使用next if $file eq '.' $file eq '..';在目录和子目录(少数目录除外)中查找文件并打开文件进行查找和替换。但是当我在文件夹名称中有点时,它会将文件夹视为一个文件并说无法打开。我使用 -f 过滤了文件,但它没有显示主文件夹中的文件。

有没有递归的方法来查找文件夹和文件,即使它有点。

opendir my $dh, $folder or die "can't open the directory: $!";

while ( defined( my $file = readdir( $dh ) ) ) {

    chomp $file;

    next if $file eq '.' $file eq '..';

    {
        if ( $file ne 'fp' ) {

            print "$folder\$file";

            if ( $file =~ m/(.[^\.]*)\.([^.]+$)/ ) {
                ...
            }
        }
    }
}

是的。使用 File::Find::Rule

foreach my $file (  File::Find::Rule->file()->in( "." ) ) {

}

...仅此而已。您几乎可以选择所有 'filetest' 标志,因此 file() 代表 -freadable() 代表 -r

您可以按照 Sobrique 的建议使用 File::Find or File::Find::Rule

使用起来非常简单:

#!/usr/bin/perl
use strict;
use warnings;
use File::Find;
sub process_file {
    next if (($_ eq '.') || ($_ eq '..'));
    if (-d && $_ eq 'fp'){
        $File::Find::prune = 1;
        return;
    }
    print "Directory: $_\n" if -d;
    print "File: $_\n" if -f;
    #Do search replace operations on file below
}
find(\&process_file, '/home/chankeypathak/Desktop/test.folder'); #provide list of paths as second argument.

我有以下文件结构。

test.folder/test.txt
test.folder/sub.folder
test.folder/sub.folder/subfile.txt
test.folder/fp
test.folder/fp/fileinsidefp.txt

我的输出低于

$ perl test.pl
File: test.txt
Directory: sub.folder
File: subfile.txt