如何使用Perl列出目录中的所有文件? [英] How can I list all of the files in a directory with Perl?

查看:107
本文介绍了如何使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆