windowsperlfile-find

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,".") ;

Solution

  • 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.