Michael Blake Michael Blake - 6 months ago 10
Perl Question

Perl directory check fail on recursive call

sub searchInDirectory
{
my @directorylist;
opendir my $dir, $_[0] or die "Unable to open directory";
while (my $file = readdir $dir)
{
if(-f "$file")
{
#process file
}
elsif((-d "$file") && !($file =~ /^\.{1,2}$/)) #directory && not .. or .
{
push @directorylist, $file;
}
}
closedir($dir);
foreach my $diritem (@directorylist)
{
&searchInDirectory($_[0] . "/" . $diritem);
}
}


This is my code for recursively traversing a directory's sub-directories and files. The problem is that it works on the first pass, but on the second call, the directory check will fail. I've checked to make sure it's identifying files vs folders correctly, which it is. It's also not failing to open the directories, so I don't get why it would fail to recognize them, and call the function again. I'd really like to stick to this method if possible instead of using other libraries.

Answer

readdir doesn't return full paths, so you need to prepend the directory before trying to do file tests:

sub searchInDirectory {
    my $path = shift;

    opendir(my $dh, $path) or die $!;
    my @files = map { "$path/$_" } grep { not /^\./ } readdir($dh);
    closedir($dh);

    for my $file (@files) {
        if (-d $file) {
            searchInDirectory($file);
        } elsif (-f $file) {
            # process file
        }
    }
}