Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl script to recursively list all filename in directory

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";
    }
}
like image 217
TopCoder Avatar asked Mar 09 '11 05:03

TopCoder


1 Answers

$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";
    }
}
like image 99
ikegami Avatar answered Sep 19 '22 04:09

ikegami