加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 打开/处理目录中所有文件的最有效方法是什么?

发布时间:2020-12-16 06:22:18 所属栏目:大数据 来源:网络整理
导读:我需要在目录的所有文件上执行我的脚本(搜索).以下是有效的方法.我只是问哪个是最好的. (我需要表单的文件名:parsedchpt31_4.txt) 水珠: my $parse_corpus; #(for all options)##glob (only if all files in same directory as script?):my @files = glob(
我需要在目录的所有文件上执行我的脚本(搜索).以下是有效的方法.我只是问哪个是最好的. (我需要表单的文件名:parsedchpt31_4.txt)

水珠:

my $parse_corpus; #(for all options)
##glob (only if all files in same directory as script?):
my @files = glob("parsed"."*.txt");
foreach my $file (@files) {
    open($parse_corpus,'<',"$file") or die $!;
     ... all my code...
}

Readdir with while和条件:

##readdir:
my $dir = '.';
opendir(DIR,$dir) or die $!;

while (my $file = readdir(DIR)) {
    next unless (-f "$dir/$file"); ##Ensure it's a file
    next unless ($file =~ m/^parsed.*.txt/); ##Ensure it's a parsed file
    open($parse_corpus,"$file") or die "Couldn't open directory $!";
     ... all my code...
}

Readdir with foreach和grep:

##readdir+grep:
my $dir = '.';
    opendir(DIR,$dir) or die $!;    
foreach my $file (grep {/^parsed.*.txt/} readdir (DIR)) {
    next unless (-f "$dir/$file"); ##Ensure it's a file
    open($parse_corpus,"$file") or die "Couldn't open directory $!";
    ... all my code...
}

文件::查找:

##File::Find
my $dir = "."; ##current directory: could be (include quotes): '/Users/jon/Desktop/...'
my @files;
find(&;open_file,$dir); ##built in function
sub open_file {
    push @files,$File::Find::name if(/^parsed.*.txt/);
}
foreach my $file (@files) {
    open($parse_corpus,"$file") or die $!;
     ...all my code...
}

还有另外一种方法吗?将我的整个脚本包含在循环中是否合适?可以,我不使用closedir吗?我把它传递给其他人,我不确定他们的文件将在哪里(可能无法使用glob)

非常感谢,希望这是一个正确的问题.

解决方法

最好或最有效的方法取决于您的目的和更大的背景.在原始速度,代码简单性或其他方面,你的意思是最好的吗?我怀疑内存考虑应该推动这种选择.目录中有多少个文件?

纯粹的实用性,glob方法运作得相当好.在诉诸任何涉及的事情之前,我会问是否有问题.

如果你能够使用其他模块,另一种方法是让别人担心肮脏的细节:

use File::Util qw();
my $fu = File::Util->new;
my @files = $fu->list_dir($dir,qw(--with-paths --files-only));

请注意,File :: Find执行递归搜索,下降到所有子目录.很多时候你不想要或不需要它.

我还要补充一点,我不喜欢你的两个readdir例子,因为它们混合了不同的功能:(1)获取文件名,(2)处理单个文件.我会将这些工作分开.

my $dir = '.';
opendir(my $dh,$dir) or die $!; # Use a lexical directory handle.
my @files = 
    grep { -f }
    map  { "$dir/$_" }
    grep { /^parsed.*.txt$/ }
    readdir($dh);

for my $file (@files){
    ...
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读