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

<p><a href="https://en.wikipedia.org/wiki/Grave_accent#Use_in_programming" rel="noreferrer">Backticks</a> can do it, but is there some method using 'scandir' or a similar term?</p>

[{'answer_id': 22573, 'author': 'jj33', 'author_id': 430, 'author_profile': 'https://Stackoverflow.com/users/430', 'pm_score': 7, 'selected': True, 'text': '<pre><code>opendir(D, "/path/to/directory") || die "Can\'t open directory: $!\\n";\nwhile (my $f = readdir(D)) {\n    print "\\$f = $f\\n";\n}\nclosedir(D);\n</code></pre>\n\n<p>EDIT: Oh, sorry, missed the "into an array" part:</p>\n\n<pre><code>my $d = shift;\n\nopendir(D, "$d") || die "Can\'t open directory $d: $!\\n";\nmy @list = readdir(D);\nclosedir(D);\n\nforeach my $f (@list) {\n    print "\\$f = $f\\n";\n}\n</code></pre>\n\n<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>\n\n<pre><code>opendir(DIR, $somedir) || die "Can\'t open directory $somedir: $!";\n@dots = grep { (!/^\\./) &amp;&amp; -f "$somedir/$_" } readdir(DIR);\nclosedir DIR;\n</code></pre>\n\n<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>\n\n<pre><code>@list = grep !/^\\.\\.?$/, readdir(D);\n</code></pre>\n\n<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>\n'}, {'answer_id': 22663, 'author': 'rix0rrr', 'author_id': 2474, 'author_profile': 'https://Stackoverflow.com/users/2474', 'pm_score': 3, 'selected': False, 'text': '<p>This will do it, in one line (note the \'*\' wildcard at the end)</p>\n\n<pre><code>@files = &lt;/path/to/directory/*&gt;;\n# To demonstrate:\nprint join(", ", @files);\n</code></pre>\n'}, {'answer_id': 22678, 'author': 'Mickey', 'author_id': 1494, 'author_profile': 'https://Stackoverflow.com/users/1494', 'pm_score': 1, 'selected': False, 'text': "<p>Here's an example of recursing through a directory structure and copying files from a backup script I wrote.</p>\n<pre><code>sub copy_directory {\nmy ($source, $dest) = @_;\nmy $start = time;\n\n# get the contents of the directory.\nopendir(D, $source);\nmy @f = readdir(D);\nclosedir(D);\n\n# recurse through the directory structure and copy files.\nforeach my $file (@f) {\n    # Setup the full path to the source and dest files.\n    my $filename = $source . &quot;\\\\&quot; . $file;\n    my $destfile = $dest . &quot;\\\\&quot; . $file;\n    \n    # get the file info for the 2 files.\n    my $sourceInfo = stat( $filename );\n    my $destInfo = stat( $destfile );\n    \n    # make sure the destinatin directory exists.\n    mkdir( $dest, 0777 );\n    \n    if ($file eq '.' || $file eq '..') {\n    } elsif (-d $filename) { # if it's a directory then recurse into it.\n        #print &quot;entering $filename\\n&quot;;\n        copy_directory($filename, $destfile); \n    } else { \n        # Only backup the file if it has been created/modified since the last backup \n        if( (not -e $destfile) || ($sourceInfo-&gt;mtime &gt; $destInfo-&gt;mtime ) ) {\n            #print $filename . &quot; -&gt; &quot; . $destfile . &quot;\\n&quot;;\n            copy( $filename, $destfile ) or print &quot;Error copying $filename: $!\\n&quot;;\n        } \n    } \n}\n\nprint &quot;$source copied in &quot; . (time - $start) . &quot; seconds.\\n&quot;;       \n}\n</code></pre>\n"}, {'answer_id': 22762, 'author': 'Gary Richardson', 'author_id': 2506, 'author_profile': 'https://Stackoverflow.com/users/2506', 'pm_score': 3, 'selected': False, 'text': '<p><a href="http://search.cpan.org/~gbarr/IO-1.2301/IO/Dir.pm" rel="nofollow noreferrer">IO::Dir</a> is nice and provides a tied hash interface as well.</p>\n\n<p>From the perldoc:</p>\n\n<pre><code>use IO::Dir;\n$d = IO::Dir-&gt;new(".");\nif (defined $d) {\n    while (defined($_ = $d-&gt;read)) { something($_); }\n    $d-&gt;rewind;\n    while (defined($_ = $d-&gt;read)) { something_else($_); }\n    undef $d;\n}\n\ntie %dir, \'IO::Dir\', ".";\nforeach (keys %dir) {\n    print $_, " " , $dir{$_}-&gt;size,"\\n";\n}\n</code></pre>\n\n<p>So you could do something like:</p>\n\n<pre><code>tie %dir, \'IO::Dir\', $directory_name;\nmy @dirs = keys %dir;\n</code></pre>\n'}, {'answer_id': 22915, 'author': 'Pat', 'author_id': 238, 'author_profile': 'https://Stackoverflow.com/users/238', 'pm_score': 4, 'selected': False, 'text': '<p>A quick and dirty solution is to use <a href="http://perldoc.perl.org/functions/glob.html" rel="noreferrer">glob</a></p>\n\n<pre><code>@files = glob (\'/path/to/dir/*\');\n</code></pre>\n'}, {'answer_id': 24436, 'author': 'trjh', 'author_id': 2620, 'author_profile': 'https://Stackoverflow.com/users/2620', 'pm_score': 1, 'selected': False, 'text': '<p>Similar to the above, but I think the best version is (slightly modified) from "perldoc -f readdir":</p>\n\n<pre><code>opendir(DIR, $somedir) || die "can\'t opendir $somedir: $!";\n@dots = grep { (!/^\\./) &amp;&amp; -f "$somedir/$_" } readdir(DIR);\nclosedir DIR;\n</code></pre>\n'}, {'answer_id': 38016, 'author': 'David Precious', 'author_id': 4040, 'author_profile': 'https://Stackoverflow.com/users/4040', 'pm_score': 3, 'selected': False, 'text': '<p>You could use <a href="http://search.cpan.org/~rgarcia/perl-5.10.0/lib/DirHandle.pm" rel="nofollow noreferrer">DirHandle</a>:</p>\n\n<pre><code>use DirHandle;\n$d = new DirHandle ".";\nif (defined $d)\n{\n    while (defined($_ = $d-&gt;read)) { something($_); }\n    $d-&gt;rewind;\n    while (defined($_ = $d-&gt;read)) { something_else($_); }\n    undef $d;\n}\n</code></pre>\n\n<p><code>DirHandle</code> provides an alternative, cleaner interface to the <code>opendir()</code>, <code>closedir()</code>, <code>readdir()</code>, and <code>rewinddir()</code> functions.</p>\n'}, {'answer_id': 42334054, 'author': 'Luke Fowler', 'author_id': 2419597, 'author_profile': 'https://Stackoverflow.com/users/2419597', 'pm_score': 0, 'selected': False, 'text': '<p>from: <a href="http://perlmeme.org/faqs/file_io/directory_listing.html" rel="nofollow noreferrer">http://perlmeme.org/faqs/file_io/directory_listing.html</a></p>\n\n<pre><code>#!/usr/bin/perl\nuse strict;\nuse warnings;\n\nmy $directory = \'/tmp\';\n\nopendir (DIR, $directory) or die $!;\n\nwhile (my $file = readdir(DIR)) {\n    next if ($file =~ m/^\\./);\n    print "$file\\n";\n}\n</code></pre>\n\n<p>The following example (based on a code sample from perldoc -f readdir) gets all the files (not directories) beginning with a period from the open directory. The filenames are found in the array @dots.</p>\n\n<pre><code>#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nmy $dir = \'/tmp\';\n\nopendir(DIR, $dir) or die $!;\n\nmy @dots \n    = grep { \n        /^\\./             # Begins with a period\n    &amp;&amp; -f "$dir/$_"   # and is a file\n} readdir(DIR);\n\n# Loop through the array printing out the filenames\nforeach my $file (@dots) {\n    print "$file\\n";\n}\n\nclosedir(DIR);\nexit 0;\n\n\nclosedir(DIR);\nexit 0;\n</code></pre>\n'}, {'answer_id': 67091406, 'author': 'Shawn', 'author_id': 9952196, 'author_profile': 'https://Stackoverflow.com/users/9952196', 'pm_score': 1, 'selected': False, 'text': '<p>You can also use the <code>children</code> method from the popular <a href="https://metacpan.org/pod/Path::Tiny" rel="nofollow noreferrer"><code>Path::Tiny</code></a> module:</p>\n<pre><code>use Path::Tiny;\nmy @files = path(&quot;/path/to/dir&quot;)-&gt;children;\n</code></pre>\n<p>This creates an array of <code>Path::Tiny</code> objects, which are often more useful than just filenames if you want to do things to the files, but if you want just the names:</p>\n<pre><code>my @files = map { $_-&gt;stringify } path(&quot;/path/to/dir&quot;)-&gt;children;\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/22566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/277/']