如何使用 Perl 列出目录中的所有文件? [英] How can I list all of the files in a directory with Perl?
问题描述
Perl 中是否有列出目录中所有文件和目录的函数?我记得 Java 有 File.list()
来做到这一点?Perl 中是否有类似的方法?
Is there a function in Perl that lists all the files and directories in a directory?
I remember that Java has the File.list()
to do this? Is there a comparable method in Perl?
推荐答案
如果你想获取给定目录的内容,并且只有它(即没有子目录),最好的方法是使用opendir/readdir/closedir:>
If you want to get content of given directory, and only it (i.e. no subdirectories), the best way is to use opendir/readdir/closedir:
opendir my $dir, "/some/path" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;
您也可以使用:
my @files = glob( $dir . '/*' );
但在我看来它不是那么好 - 主要是因为 glob 是非常复杂的东西(可以自动过滤结果)并且使用它来获取目录的所有元素似乎是一项过于简单的任务.
But in my opinion it is not as good - mostly because glob is quite complex thing (can filter results automatically) and using it to get all elements of directory seems as a too simple task.
另一方面,如果您需要从所有目录和子目录中获取内容,基本上有一个标准解决方案:
On the other hand, if you need to get content from all of the directories and subdirectories, there is basically one standard solution:
use File::Find;
my @content;
find( &wanted, '/some/path');
do_something_with( @content );
exit;
sub wanted {
push @content, $File::Find::name;
return;
}
这篇关于如何使用 Perl 列出目录中的所有文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!