代码之家  ›  专栏  ›  技术社区  ›  chappar

如何从所需函数中打开file::Find找到的文件?

  •  1
  • chappar  · 技术社区  · 17 年前

    $File::Find::name (在这种情况下 ./tmp/tmp.h )在我的 search 函数(由调用 File::Find::find ),它说“无法打开文件.tmp/tmp.h原因=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 回复  |  直到 12 年前
        1
  •  10
  •   Sinan Ünür    17 年前

    perldoc File::Find File::Find::find $File::Find::name 包含相对于搜索开始位置的文件路径。当前目录更改后无法使用的路径。

    您有两个选择:

    1. 告诉文件::查找不更改到它搜索的目录: find( { wanted => \%search, no_chdir => 1 }, '.' );
    2. 或者不使用 但是 $_
        2
  •  0
  •   AndyG    9 年前

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

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

        3
  •  -1
  •   Space    17 年前

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