我正在开发Perl中的一个递归文件查找函数,该函数应该返回一个文件名数组。然而,当我尝试打印它们时,我得到的却是0。我做错了什么?
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";
}
}发布于 2011-11-27 05:21:22
这里的主要问题是像这样的行:
getfn($line, $path);什么也做不了。它会找到子目录中的所有文件,但随后会将它们完全丢弃。您需要将其返回值合并到外部调用的@fns中。
第二个问题是:
print &getfn($f, $ENV{PWD})."\n";强制将返回的数组视为标量,因此它打印数组元素的数量,而不是数组元素的内容。你可能想要这样的东西:
print "$_\n" foreach getfn($f, $ENV{PWD});发布于 2011-11-27 05:17:49
当您以递归方式调用getfn()时,不会将返回的数组赋给任何对象。你唯一的任务是:
my @fns = ();在函数的顶部,这就是返回的内容。
https://stackoverflow.com/questions/8281649
复制相似问题