如何使用Perl列出目录中的所有文件? [英] How can I list all files in a directory using Perl?
问题描述
我通常会使用
my $dir="/path/to/dir";
opendir(DIR, $dir) or die "can't open $dir: $!";
my @files = readdir DIR;
closedir DIR;
或有时我使用 glob
,但无论如何,我总是需要添加一两行来过滤掉。
和 ..
这是非常烦人的。
你通常如何处理这个常见的任务?
or sometimes I use glob
, but anyway, I always need to add a line or two to filter out .
and ..
which is quite annoying.
How do you usually go about this common task?
推荐答案
我通常会使用对于我的$文件(glob$ dir / *){
$ b
I will normally use the glob
method:
for my $file (glob "$dir/*") {
#do stuff with $file
}
这工作正常,除非目录有很多的文件。在这些情况下,您必须在中切换回
循环(将 readdir
,而 readdir
在列表上下文中与 glob
一样糟糕):
This works fine unless the directory has lots of files in it. In those cases you have to switch back to readdir
in a while
loop (putting readdir
in list context is just as bad as the glob
):
open my $dh, $dir
or die "could not open $dir: $!";
while (my $file = readdir $dh) {
next if $file =~ /^[.]/;
#do stuff with $file
}
通常,如果我在目录中读取一堆文件,我想以递归的方式读取它们。在这些情况下,我使用 File :: Find
:
Often though, if I am reading a bunch of files in a directory, I want to read them in a recursive manner. In those cases I use File::Find
:
use File::Find;
find sub {
return if /^[.]/;
#do stuff with $_ or $File::Find::name
}, $dir;
这篇关于如何使用Perl列出目录中的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!