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

Question :

How do I read in the contents of a directory in Perl?,

Answer :

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

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 = $fn";  }  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 = $fn";  }  

EDIT2: Most of the other answers are valid, but I wanted to comment on 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 () through a  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 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.

Read More  My regex is matching too much. How do I make it stop?

That’s the answer How do I read in the contents of a directory in Perl?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you