chappar
chappar

Reputation: 7505

How can I open a file found by File::Find from inside the wanted function?

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

Answers (3)

draegtun
draegtun

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

innaM
innaM

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:

  1. Tell File::Find to not change to the directories it searches: find( { wanted => \%search, no_chdir => 1 }, '.' );
  2. Or don't use $File::Find::name, but $_ instead.

Upvotes: 10

Space
Space

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

Related Questions