sách gpt4 ai đã đi

perl - 打开/操作目录中所有文件的最有效方法是什么?

In lại 作者:行者123 更新时间:2023-12-04 10:38:32 33 4
mua khóa gpt4 Nike

我需要对目录的所有文件执行我的脚本(搜索)。以下是有效的方法。我只是问哪个最好。 (我需要格式的文件名: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...
}

带有 while 和条件的 Readdir:
##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...
}

使用 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...
}

还有其他方法吗?将我的整个脚本包含在循环中是否很好?我不使用closeir可以吗?我将其传递给其他人,我不确定他们的文件将在哪里(可能无法使用 glob)

非常感谢,希望这是问这个问题的正确地方。

1 Câu trả lời

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

为了纯粹的实用性,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){
...
}

关于perl - 打开/操作目录中所有文件的最有效方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6324634/

33 4 0
行者123
Hồ sơ cá nhân

Tôi là một lập trình viên xuất sắc, rất giỏi!

Nhận phiếu giảm giá Didi Taxi miễn phí
Mã giảm giá Didi Taxi
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com