如何使用 Perl 列出目录中的所有文件?
我通常使用类似的东西
my $dir="/path/to/dir";
opendir(DIR, $dir) or die "can't open $dir: $!";
my @files = readdir DIR;
closedir DIR;
,有时我使用 glob
,但无论如何,我总是需要添加一两行来过滤掉 .
和 ..
这很烦人。 您通常如何完成这项常见任务?
I usually use something like
my $dir="/path/to/dir";
opendir(DIR, $dir) or die "can't open $dir: $!";
my @files = readdir DIR;
closedir DIR;
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这也将排除所有点文件,但这通常就是您想要的。
This will exclude all the dotfiles as well, but that's usually What You Want.
我经常使用 File::Slurp。好处包括: (1) 如果目录不存在则自动终止。 (2) 默认排除
.
和..
。它的行为类似于 readdir ,因为它不返回完整路径。另一个有用的模块是 File::Util,它在读取目录时提供了许多选项。例如:
I often use File::Slurp. Benefits include: (1) Dies automatically if the directory does not exist. (2) Excludes
.
and..
by default. It's behavior is likereaddir
in that it does not return the full paths.Another useful module is File::Util, which provides many options when reading a directory. For example:
我通常会使用
glob
方法:除非目录中有很多文件,否则这种方法可以正常工作。在这些情况下,您必须在
while
循环中切换回readdir
(将readdir
放入列表上下文中与glob
):但通常,如果我正在读取目录中的一堆文件,我想以递归方式读取它们。在这些情况下,我使用
File::Find
:I will normally use the
glob
method:This works fine unless the directory has lots of files in it. In those cases you have to switch back to
readdir
in awhile
loop (puttingreaddir
in list context is just as bad as theglob
):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
:如果某些点文件很重要,
则仅排除
.
和..
If some of the dotfiles are important,
will only exclude
.
and..
当我只想要文件(而不是目录)时,我使用
grep
和-f
测试:When I just want the files (as opposed to directories), I use
grep
with a-f
test:感谢克里斯和以太的建议。我使用以下命令将所有文件(排除的目录)的列表从引用当前目录以外的目录的目录句柄读取到数组中。 grep 语句中不使用绝对路径时,数组总是缺少一个文件
Thanks Chris and Ether for your recommendations. I used the following to read a listing of all files (excluded directories), from a directory handle referencing a directory other than my current directory, into an array. The array was always missing one file when not using the absolute path in the grep statement