Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

file io - How do I read in the contents of a directory in Perl?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
opendir(D, "/path/to/directory") || die "Can't open directory: $!
";
while (my $f = readdir(D)) {
    print "$f = $f
";
}
closedir(D);

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

my $d = shift;

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...