如何在 Perl 中读入目录的内容? [英] How do I read in the contents of a directory in Perl?
问题描述
如何让 Perl 将给定目录的内容读入数组?
How do I get Perl to read the contents of a given directory into an array?
反引号可以做到,但是有没有一些方法使用scandir"或相似词?
Backticks can do it, but is there some method using 'scandir' or a similar term?
推荐答案
opendir(D, "/path/to/directory") || die "Can't open directory: $!
";
while (my $f = readdir(D)) {
print "$f = $f
";
}
closedir(D);
哦,抱歉,错过了放入数组"部分:
Oh, sorry, missed the "into an array" part:
my $d = shift;
opendir(D, "$d") || die "Can't open directory $d: $!
";
my @list = readdir(D);
closedir(D);
foreach my $f (@list) {
print "$f = $f
";
}
大多数其他答案都是有效的,但我想评论 这个答案,其中提供了这个解决方案:
Most of the other answers are valid, but I wanted to comment on this answer specifically, in which this solution is offered:
opendir(DIR, $somedir) || die "Can't open directory $somedir: $!";
@dots = grep { (!/^./) && -f "$somedir/$_" } readdir(DIR);
closedir DIR;
首先,记录它在做什么,因为海报没有:它正在传递从 返回的列表readdir() 通过 grep() 只返回那些值文件(相对于目录、设备、命名管道等)并且不以点开头(这使得列表名称 @dots
具有误导性,但这是由于他在复制时所做的更改它来自 readdir() 文档).由于它限制了它返回的目录的内容,我认为这在技术上不是这个问题的正确答案,但它说明了用于过滤 Perl,我认为记录下来会很有价值.另一个经常看到的例子是:
First, to document what it's doing since the poster didn't: it's passing the returned list from readdir() through a grep() that only returns those values that are files (as opposed to directories, devices, named pipes, etc.) and that do not begin with a dot (which makes the list name @dots
misleading, but that's due to the change he made when copying it over from the readdir() documentation). Since it limits the contents of the directory it returns, I don't think it's technically a correct answer to this question, but it illustrates a common idiom used to filter filenames in Perl, and I thought it would be valuable to document. Another example seen a lot is:
@list = grep !/^..?$/, readdir(D);
此代码段从目录句柄 D 除了 '.' 读取所有内容.和..",因为它们很少需要在列表中使用.
This snippet reads all contents from the directory handle D except '.' and '..', since those are very rarely desired to be used in the listing.
这篇关于如何在 Perl 中读入目录的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!