【问题标题】:Find::File to search a directory of a list of filesFind::File 搜索文件列表的目录
【发布时间】:2012-11-08 18:46:21
【问题描述】:

我正在编写一个 Perl 脚本,而且我是 Perl 的新手——我有一个包含文件列表的文件。对于列表中的每个项目,我想搜索给定目录及其子目录以查找文件返回完整路径。到目前为止,我一直没有成功尝试使用 File::Find。这是我得到的:

use strict;
use warnings;
use File::Find;

my $directory = '/home/directory/';
my $input_file = '/home/directory/file_list'; 
my @file_list;


find(\&wanted, $directory);

sub wanted {
    open (FILE, $input_file);

    foreach my $file (<FILE>) {
        chomp($file);

        push ( @file_list, $file );
    }   

    close (FILE);

    return @file_list;
}

【问题讨论】:

    标签: perl


    【解决方案1】:

    我发现 File::Find::Rule 使用起来更简单、更优雅。

    use File::Find::Rule;
    
    my $path = '/some/path';
    # Find all directories under $path
    my @paths = File::Find::Rule->directory->in( $path );
    # Find all files in $path
    my @files = File::Find::Rule->file->in( $path );
    

    数组包含 File::Find::Rule 找到的对象的完整路径。

    【讨论】:

    • 感谢Rule 的提醒,我去看看。
    【解决方案2】:

    File::Find 用于遍历文件系统中的目录结构。而不是做你想做的事,即在文件中读取想要的子例程,你应该按如下方式读取文件:

    use strict;
    use warnings;
    use vars qw/@file_list/;
    
    my $directory = '/home/directory/';
    my $input_file = '/home/directory/file_list'; 
    open FILE, "$input_file" or die "$!\n";
    foreach my $file (<FILE>) {
        chomp($file);
    
        push ( @file_list, $file );
    } 
    # do what you need to here with the @file_list array
    

    【讨论】:

    • 我相信File::Find 需要wanted 子例程。至少当我拉出数组并尝试直接传递它时,我得到:“在 /System/Library/Perl/5.12/File/Find.pm 第 1291 行没有给出 &wanted 子例程。”
    【解决方案3】:

    好的,重新阅读文档,我误解了wanted 子例程。 wanted 是一个对找到的每个文件和目录调用的子例程。所以这是我的代码来考虑这一点

    use strict;
    use warnings;
    use File::Find;
    
    my $directory = '/home/directory/';
    my $input_file = '/home/directory/file_list';
    my @file_list;
    
    open (FILE, $input_file);
    
    foreach my $file (<FILE>) {
        chomp($file);
    
        push ( @file_list, $file );
    }   
    
    close (FILE);
    
    find(\&wanted, $directory);
    
    sub wanted {
        if ( $_ ~~ @file_list ) { 
            print "$File::Find::name\n";
        }   
        return;
    }
    

    【讨论】:

    • 史蒂夫,你应该编辑你的问题,而不是自己回答。
    • @hd1,假设这可以解决问题,那么操作员可以发布解决方案。编辑问题是为了当仍然存在问题时
    • 那是非常低效的。将push 行更改为++$file_list{$file}; 并将~~ 行更改为if ($file_list{$_})
    猜你喜欢
    • 2018-12-27
    • 2016-08-22
    • 2014-11-12
    • 1970-01-01
    • 2023-02-02
    • 1970-01-01
    • 2016-11-27
    • 2023-03-24
    • 2015-08-02
    相关资源
    最近更新 更多