perl script to recursively list all filename in directory

TopCoder picture TopCoder · Mar 9, 2011 · Viewed 29.6k times · Source

I have written following perl script but problem is its always going in else part and reporting not a file. I do have files in the directory which I am giving in input. What am I doing wrong here?

My requirement is to recursively visit every file in a directory, open it and read it in a string. But the first part of the logic is failing.

#!/usr/bin/perl -w
use strict;
use warnings;
use File::Find;

my (@dir) = @ARGV;
find(\&process_file,@dir);

sub process_file {
    #print $File::Find::name."\n";
    my $filename = $File::Find::name;
    if( -f $filename) {
        print " This is a file :$filename \n";
    } else {
        print " This is not file :$filename \n";
    }
}

Answer

ikegami picture ikegami · Mar 9, 2011

$File::Find::name gives the path relative to original working directory. However, File::Find keeps changing the current working directory unless you tell it otherwise.

Either use the no_chdir option, or use -f $_ which contains just the file name portion. I recommend the former.

#!/usr/bin/perl -w
use strict; 
use warnings;
use File::Find;

find({ wanted => \&process_file, no_chdir => 1 }, @ARGV);

sub process_file {
    if (-f $_) {
        print "This is a file: $_\n";
    } else {
        print "This is not file: $_\n";
    }
}