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

VSr*_*VSr 2 perl perl-module

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/(.[^\.]*)\.([^.]+$)/ ) {
                ...
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Cha*_*hak 5

您可以使用Sobrique建议的File :: FindFile :: 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.
Run Code Online (Sandbox Code Playgroud)

我有以下文件结构.

test.folder/test.txt
test.folder/sub.folder
test.folder/sub.folder/subfile.txt
test.folder/fp
test.folder/fp/fileinsidefp.txt
Run Code Online (Sandbox Code Playgroud)

我得到了低于输出

$ perl test.pl
File: test.txt
Directory: sub.folder
File: subfile.txt
Run Code Online (Sandbox Code Playgroud)