perl script to recursively list all filename in directory

29,571

$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";
    }
}
Share:
29,571

Related videos on Youtube

TopCoder
Author by

TopCoder

Updated on July 09, 2022

Comments

  • TopCoder
    TopCoder almost 2 years

    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";
        }
    }
    
    • mu is too short
      mu is too short about 13 years
      @TopCoder: That's the version of which, you want just perl --version or perl -V, or perhaps $(which perl) --version or $(which perl) -V if perl is not in your PATH.
  • FMc
    FMc about 13 years
    My mistake! Deleted bogus comment and +1.

Related