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

时间:2009-08-19 09:17:05

标签: windows perl file-find

我的代码如下。如果我在$File::Find::name函数(由./tmp/tmp.h调用)中打开文件search(在本例中为File::Find::find),则表示“无法打开文件./tmp /tmp.h reason = temp.pl第36行第98行没有这样的文件或目录。“

如果我直接在另一个函数中打开文件,我可以打开该文件。 有人能告诉我这种行为的原因吗?我在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,".") ;

3 个答案:

答案 0 :(得分:10)

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

您有两种选择:

  1. 告诉文件::查找不更改为其搜索的目录:find( { wanted => \%search, no_chdir => 1 }, '.' );
  2. 或者不要使用$File::Find::name,而是使用$_

答案 1 :(得分:0)

如果 ./ tmp / 是符号链接,那么您需要执行以下操作:

find( { wanted => \&search, follow => 1 }, '.' );

这有帮助吗?

答案 2 :(得分:-1)

如果要在当前工作目录中搜索文件,可以使用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") ;