Reputation: 7505
I have code like below. If I open the file $File::Find::name
(in this case it is ./tmp/tmp.h
) in my search
function (called by File::Find::find
), it says "cannot open the file ./tmp/tmp.h reason = No such file or directory at temp.pl line 36, line 98."
If I open the file directly in another function, I am able open the file. Can somebody tell me the reason for this behavior? I am using activeperl on Windows and the version is 5.6.1.
use warnings;
use strict;
use File::Find;
sub search
{
return unless($File::Find::name =~ /\.h\s*$/);
open (FH,"<", "$File::Find::name") or die "cannot open the file $File::Find::name reason = $!";
print "open success $File::Find::name\n";
close FH;
}
sub fun
{
open (FH,"<", "./tmp/tmp.h") or die "cannot open the file ./tmp/tmp.h reason = $!";
print "open success ./tmp/tmp.h\n";
close FH;
}
find(\&search,".") ;
Upvotes: 1
Views: 475
Reputation: 22560
If ./tmp/ is a symbolic link then you will need to do following:
find( { wanted => \&search, follow => 1 }, '.' );
Does that help?
Upvotes: 0
Reputation: 47829
See perldoc File::Find
: The wanted function (search in your case) will be called after File::Find::find
changed to the directory that is currently searched. As you can see, $File::Find::name
contains the path to the file relative to where the search started. That path that won't work after the current directory changes.
You have two options:
find( { wanted => \%search, no_chdir => 1 }, '.' );
$File::Find::name
, but $_
instead.Upvotes: 10
Reputation: 7259
If you want to search the file in current working dir you can use Cwd.
use warnings;
use strict;
use File::Find;
use Cwd;
my $dir = getcwd;
sub search
{
return unless($File::Find::name =~ /\.h\s*$/);
open (FH,"<", "$File::Find::name") or die "cannot open the file $File::Find::name reason = $!";
print "open success $File::Find::name\n";
close FH;
}
find(\&search,"$dir") ;
Upvotes: -1