VSe
VSe

Reputation: 929

Find files in the folder and subfolder

I am using next if $file eq '.' $file eq '..'; to find the file in the directory and subdirectory(except few directories) and opening the files for find and replacement. But when I have dot in folder name, it consider the folder as a file and says can't open. I filtered the files using -f but it missing to show the files in the main folder.

Is there any recursive way to find the folder and files even it has dot.

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

Upvotes: 2

Views: 2920

Answers (2)

Chankey Pathak
Chankey Pathak

Reputation: 21676

You could use File::Find or File::Find::Rule as suggested by Sobrique.

It's very easy to use:

#!/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.

I had below file structure.

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

And I got below output

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

Upvotes: 5

Sobrique
Sobrique

Reputation: 53508

Yes. Use File::Find::Rule

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

}

... and that's about it. You've got options for pretty much all the 'filetest' flags, so file() for -f or readable() for -r.

Upvotes: 4

Related Questions