我正在研究Perl中的递归文件查找功能,它应该返回一个文件名数组。但是,当我尝试打印它们时,会发生什么,我只是得到0
。我究竟做错了什么?在Perl中返回数组
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";
}
}
你看过File :: Find :: Closures?你可能不需要做任何工作,或者通过从中窃取代码来做很少的工作。 :) –