Reading directories is a bit more complicated than just opendir/readdir/closedir, especially if you want to recurse into subdirectories and follow common conventions like ignoring files that start with a dot (Linux/Unix "hidden" files).
There are modules like File::Find that can do a lot of the magic for you. But if you want do more complicated stuff, you may or may not have to roll your own. For example, handling files as you see them (a tactic i use in my own frameworks, especialy when i need to do a lot of processing per file or need complicated search rules) or deciding if you want to read certain directories depending on config options in a database or something like that.
Here's a simple example code of how to recursively iterate through subdirectories. Note that i only have one directory handle open at any one time, to avoid running out of open file handles (Let a bunch of Microsoft Office users get access to a shared drive for a decade and you get directory structures deeper than the Mariana Trench.)
#!/usr/bin/env perl
use v5.36;
use strict;
use warnings;
use Data::Dumper;
use Carp;
use English;
my $dirfname = "."; # Start with working directory
my @files = findFiles($dirfname);
print Dumper(\@files);
exit(0);
sub findFiles($basedir) {
my @fnames;
my @dnames;
opendir(my $dfh, $basedir) or croak($ERRNO);
while((my $fname = readdir $dfh)) {
if($fname =~ /^\./) {
# Ignore "hidden" files
next;
}
my $fullname = $basedir . '/' . $fname;
if(-d $fullname) {
push @dnames, $fullname;
} elsif(-f $fullname) {
push @fnames, $fullname;
} else {
# It is something else, like a softlink. Ignore it for now
}
}
closedir $dfh;
# Only recurse AFTER closing the current dir, this way we won't ex
+ceed filehandle maximums
foreach my $dname (@dnames) {
push @fnames, findFiles($dname);
}
return @fnames;
}
|