Senthil Senthil - 6 months ago 50
Perl Question

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


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

It's very easy to use:

use strict;
use warnings;
use File::Find;
sub process_file {
    next if (($_ eq '.') || ($_ eq '..'));
    if (-d && $_ eq 'fp'){
        $File::Find::prune = 1;
    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.


And I got below output

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