Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>opendir(D, "/path/to/directory") || die "Can't open directory: $!\n"; while (my $f = readdir(D)) { print "\$f = $f\n"; } closedir(D); </code></pre> <p>EDIT: Oh, sorry, missed the "into an array" part:</p> <pre><code>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"; } </code></pre> <p>EDIT2: Most of the other answers are valid, but I wanted to comment on <a href="https://stackoverflow.com/questions/22566/how-do-i-read-in-the-contents-of-a-directory-in-perl#24436">this answer</a> specifically, in which this solution is offered:</p> <pre><code>opendir(DIR, $somedir) || die "Can't open directory $somedir: $!"; @dots = grep { (!/^\./) &amp;&amp; -f "$somedir/$_" } readdir(DIR); closedir DIR; </code></pre> <p>First, to document what it's doing since the poster didn't: it's passing the returned list from <a href="http://perldoc.perl.org/functions/readdir.html" rel="noreferrer">readdir()</a> through a <a href="http://perldoc.perl.org/functions/grep.html" rel="noreferrer">grep()</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 <code>@dots</code> 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 <a href="http://en.wikipedia.org/wiki/Perl" rel="noreferrer">Perl</a>, and I thought it would be valuable to document. Another example seen a lot is:</p> <pre><code>@list = grep !/^\.\.?$/, readdir(D); </code></pre> <p>This snippet reads all contents from the directory handle D <strong>except</strong> '.' and '..', since those are very rarely desired to be used in the listing.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload