tek*_*agi 0 arrays perl return function subroutine
我正在研究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";
}
}
Run Code Online (Sandbox Code Playgroud)
这里的主要问题是这样的一行:
getfn($line, $path);
Run Code Online (Sandbox Code Playgroud)
什么都不做 它找到子目录中的所有文件,但随后它会完全丢弃它们.您需要将其返回值合并到外部调用中@fns.
第二个问题是:
print &getfn($f, $ENV{PWD})."\n";
Run Code Online (Sandbox Code Playgroud)
强制将返回的数组视为标量,因此它会打印数组元素的数量而不是数组元素的内容.你可能想要这样的东西:
print "$_\n" foreach getfn($f, $ENV{PWD});
Run Code Online (Sandbox Code Playgroud)