如何读取Perl中的目录内容? [英] How do I read in the contents of a directory in Perl?

查看:143
本文介绍了如何读取Perl中的目录内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何让Perl将给定目录的内容读入数组?

Backticks 可以做到这一点,但是有没有使用'scandir'或类似术语的方法?

解决方案

  opendir(D,/ path / to / directory)||死无法打开目录:$!\\\
;
while(my $ f = readdir(D)){
print\ $ f = $ f \\\
;
}
closedir(D);

编辑:哦,对不起,错过了进入数组的部分:

  my $ d = shift; 

opendir(D,$ d)||死无法打开目录$ d:$!\\\
;
my @list = readdir(D);
closedir(D);

foreach my $ f(@list){
print\ $ f = $ f \\\
;





编辑2:大部分其他答案是有效的,但我想评论这个答案特别是,在这个解决方案提供:

  opendir(DIR,$ somedir)||死无法打开目录$ somedir:$!; 
@dots = grep {(!/ ^ \。/)&& -f$ somedir / $ _} readdir(DIR);
closedir DIR;首先,要记录下它做了什么,因为海报没有:它将返回的列表传递给

$ b $>通过一个。 /functions/grep.htmlrel =nofollow noreferrer> grep(),它只返回文件的值(与目录,设备,命名管道等相对),而不是以(这使得列表名称 @dots 具有误导性,但是这是由于从readdir()文档复制它时所做的更改)。由于它限制了它返回的目录的内容,我不认为这在技术上是对这个问题的正确答案,但是它说明了一个常用的习惯用来过滤 Perl ,我认为这将是有价值的文件。另一个很常见的例子是:
$ b $ $ p $ @list = grep!/ ^ \\。$ /,readdir d);

这段代码读取目录句柄D 中除'之外的所有内容。和'..',因为这些是非常罕见的需要在列表中使用


How do I get Perl to read the contents of a given directory into an array?

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: $!\n";
while (my $f = readdir(D)) {
    print "\$f = $f\n";
}
closedir(D);

EDIT: Oh, sorry, missed the "into an array" part:

my $d = shift;

opendir(D, "$d") || die "Can't open directory $d: $!\n";
my @list = readdir(D);
closedir(D);

foreach my $f (@list) {
    print "\$f = $f\n";
}

EDIT2: 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;

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);

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屋!

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