15

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";
    }
}
Sai Nikhil
  • 1,237
  • 2
  • 15
  • 39
TopCoder
  • 4,206
  • 19
  • 52
  • 64
  • This code seems to work perfectly fine for me (ActiveState Perl 5.10 on XP). How are you calling your script? What *exactly* do you mean by "But the first part of the logic is failing."? – DVK Mar 09 '11 at 05:36
  • Which platform are you using? Which perl version? – weismat Mar 09 '11 at 05:36
  • "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." By First part of the logic I meant , visit every file in directory. File check is failing for me. – TopCoder Mar 09 '11 at 05:39
  • 1
    @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`. – mu is too short Mar 09 '11 at 05:40
  • sorry , this is the correct version : perl, v5.8.8 built for x86_64-linux-thread-multi – TopCoder Mar 09 '11 at 05:41
  • Any idea what I am doing wrong here ? – TopCoder Mar 09 '11 at 05:45
  • @TopCoder - "failing" doesn't mean anything. Please specify *technical* details of what you expect the script to do on a specific example and what it does differently. – DVK Mar 09 '11 at 15:02

1 Answers1

27

$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";
    }
}
FMc
  • 41,963
  • 13
  • 79
  • 132
ikegami
  • 367,544
  • 15
  • 269
  • 518