I’m working on a recursive file-finding function in Perl that’s supposed to return an array of filenames. What happens, though, is when I try to print them, I just get 0. What am I doing wrong?
use strict;
use File::Basename;
use constant debug => 0;
sub isdir {
return (-d $_[0]);
}
sub isfile {
return (-f $_[0]);
}
my $level = 0;
#my @fns = ();
sub getfn {
my @fns = ();
my($file, $path) = @_;
my (undef, undef, $ext) = fileparse($file, qr"\.[^.]+$");
$level++;
print "-->>getfn($level): $file : $path\n" if debug;
print "arg:\t$file\t$path ($ext)\n" if debug;
if ($ext eq ".bragi") {
open my $FILE, "<", "$path/$file" or die "Failed to open $path/$file: $!";
my @lines = <$FILE>;
close $FILE;
foreach my $line (@lines) {
chomp($line);
my $fullpath = "$path/$line";
print "---- $fullpath\n" if debug;
if (isfile($fullpath)) {
#print "file:\t$fullpath\n";
push(@fns, $fullpath);
getfn($line, $path);
}
elsif (isdir($fullpath)) {
#print "DIR:\t$fullpath\n";
opendir my ($dh), $fullpath or
die "$fullpath does not exist or is not a directory: $!";
my @files = readdir $dh;
closedir $dh;
foreach my $f (@files) {
getfn($f, "$fullpath");
}
}
}
}
print "<<--getfn($level)\n" if debug;
$level--;
#print @fns;
return @fns;
}
foreach my $f (<*>) {
#print "fn: ".$f."\n";
my (undef, undef, $ext) = fileparse($f, qr"\.[^.]+$");
if ($ext eq ".bragi") {
print &getfn($f, $ENV{PWD})."\n";
}
}
The main problem here is that a line like this:
doesn’t really do anything. It finds all the files in the subdirectory, but then it completely discards them. You need to incorporate its return value into your outer call’s
@fns.A second problem is that this:
forces the returned array to be treated as a scalar, so it prints the number of array elements rather than the contents of the array elements. You probably want something like this: