迭代查找XML文件的所有子目录 - Perl

时间:2012-08-23 13:35:11

标签: xml perl

我正在尝试实现一个迭代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。我怎么能做到这一点?

2 个答案:

答案 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
);