1

我正在尝试实现一个过程,该过程遍历目录中的所有subdirectories内容,在.root.xmlPerl

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发送dirpathto getXMLFiles。我怎么能做到这一点?

4

2 回答 2

1

$File::Find::dir是当前目录名。您可以在 sub 中使用该变量wanted并将其传递给您调用的 subs。有关所需功能的更多信息,请参阅文档

这应该有效:

sub iterateDir {
    my $current_dir = $_[ 0 ];
    finddepth( \&wanted, $current_dir );
    #                                    |
    # pass current dir to getXMLFiles    V
    sub wanted{ print getXMLFiles($File::Find::dir) }
}
于 2012-08-23T13:44:41.023 回答
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
);
于 2012-08-23T13:50:31.687 回答