如何从想要的函数中打开File :: Find找到的文件?

cha*_*par 1 windows perl file-find

我有如下代码.如果我在我的函数中打开文件$File::Find::name(在这种情况下它是./tmp/tmp.h),它会说"无法打开文件./tmp/tmp.h reason =在temp.pl第36行第98行没有这样的文件或目录".searchFile::Find::find

如果我直接在另一个函数中打开文件,我可以打开该文件.有人能告诉我这种行为的原因吗?我在Windows上使用activeperl,版本是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,".") ;
Run Code Online (Sandbox Code Playgroud)

inn*_*naM 10

请参阅perldoc File::Find:在File::Find::find更改为当前搜索的目录后,将调用所需函数(在您的情况下搜索).如您所见,$File::Find::name包含相对于搜索开始位置的文件路径.当前目录更改后无效的路径.

您有两种选择:

  1. Tell File :: Find不改变它搜索的目录: find( { wanted => \%search, no_chdir => 1 }, '.' );
  2. 或者不要使用$File::Find::name,而是使用$_.