我正在尝试实现一个迭代subdirectories
目录中所有root
的过程,在.xml
中查找Perl
个文件。
sub getXMLFiles {
my $current_dir = $_[ 0 ];
opendir my $dir, $current_dir or die "Cannot open directory: $!\n";
my @files = grep /\.xml$/i, readdir $dir;
closedir $dir;
return @files;
}
sub iterateDir {
my $current_dir = $_[ 0 ];
finddepth( \&wanted, $current_dir );
sub wanted{ print getXMLFiles }
}
#########################################################
# #
# define the main subroutine. #
# first, it figures from where it is being ran #
# then recursively iterates over all the subdirectories #
# looking for .xml files to be reformatted #
# #
#########################################################
sub main(){
#
# get the current directory in which is the
# program running on
#
my $current_dir = getcwd;
iterateDir( $current_dir );
}
#########################################################
# #
# call the main function of the program #
# #
#########################################################
main();
我对Perl
不太熟悉。 sub iterateDir
过程应该遍历子目录,而getXMLFiles
将过滤.xml
个文件,并返回它们。我会使用那些.xml
文件进行解析。这就是我试图从.xml
目录中找到所有root
文件的原因。
但是,我不知道如何使用sub wanted
内的iterateDir
程序将dirpath
发送给getXMLFiles
。我怎么能做到这一点?
答案 0 :(得分:1)
$File::Find::dir
是当前目录名称。您可以在wanted
子中使用该变量,并将其传递给您调用的子。有关the wanted function
这应该有效:
sub iterateDir {
my $current_dir = $_[ 0 ];
finddepth( \&wanted, $current_dir );
# |
# pass current dir to getXMLFiles V
sub wanted{ print getXMLFiles($File::Find::dir) }
}
答案 1 :(得分:0)
另一种方式......
use warnings;
use strict;
use File::Find;
use Cwd;
my $current_dir = getcwd();
my @files;
find(
{
wanted => sub { push @files, $_ if -f $_ and /\.xml$/i },
no_chdir => 1,
},
$current_dir
);