通过递归查找和替换Perl脚本传递数组

时间:2013-03-25 21:13:08

标签: arrays perl replace

我有一个'users-tb-deleted.txt'文件,这是一个用户列表,以换行符分隔,需要从目录结构中的大约50个文件中删除。

如何打开大量文件并使用之前的列表进行查找和替换,而不编写50个不同的文件句柄参数,这些参数都执行相同的操作?

当前代码:

use File::Find;
open(FILE, "$path/delete-list.txt") || die "$!\n";
my @user = <FILE>;
close(FILE);
---
opendir(DIR, "/path/to/dir") || die "$!\n";
@docs= grep(/\.uid$/,readdir(DIR));    
foreach $file {
    open (RES, $file) || die "$!\n";
    while(<RES>){
        foreach $user (@user){
            chomp;
            s/$user//ig;
        }
    }
}

任何想法,想法和建议?

2 个答案:

答案 0 :(得分:0)

use File::Find;
use Tie::File;

... # define $path and @dirs and &some_condition;

open(FILE, "$path/delete-list.txt") || die "$!\n";
my @user = <FILE>;
close(FILE); 
my $regex = join "|", @user;

find(\&wanted, @dirs);

sub wanted {
    my $full_path = $File::Find::name;
    next if -d $full_path;
    next unless &some_condition($full_path);

    tie my @lines, $full_path or die $!;

    for my $line (@lines) {
        $line =~ s/($regex)//ig;
    }

    untie @lines;
}

答案 1 :(得分:0)

请注意

opendir(DIR, "/path/to/dir") || die "$!\n";
@docs= grep(/\.uid$/,readdir(DIR));

更容易阅读

@docs = glob( '/path/to/dir/*.uid' );