我想编写一个遍历目录及其子目录的脚本,抓取所有XML文件并解析它们。我遇到了chdir
的问题。这很好用:
my $search = "/home/user/books";
chdir($search) or die "cant change dir to $search $!";
system("ls");
但我希望用户决定他想要搜索的路径,以便我使用Getopt::Long
:
use strict;
use warnings;
use Data::Dumper;
use XML::Simple;
use Getopt::Long;
my $outputFile = '';
my $searchPath = "";
my $debug = 0;
GetOptions('outputFile=s' => \$outputFile, 'searchPath=s' => \$searchPath);
if ($outputFile eq '' or $searchPath = '') {
die("parameter --outpulFile=s is required.");
}
$searchPath =~ s/\/*$/\//;
my @founddirs = `cd $searchPath`;
foreach my $foundfiles (@founddirs) {
print $foundfiles;
chdir($foundfiles) or die "cant change dir to $searchPath $!";
chdir('..');
}
要运行的命令:
perl sample.pl --outputFile=books.txt --searchPath=/home/user/june18
我想从子目录中获取所有recursive.xml文件并解析它们。有谁知道如何做到这一点?
答案 0 :(得分:1)
这里有几个问题:
$searchPath = ''
在输入验证期间将搜索路径设置为空字符串。请改为使用eq
(不是==
) @founddirs
将不包含任何内容,因为反引号操作符不会返回任何内容。这是因为
my @founddirs = `cd $searchPath`;
不会打印由换行符分隔的找到的目录。也许你在ls $searchPath
另外,为什么不使用File::Find
?
use strict;
use warnings;
use File::Find;
use Getopt::Long;
my $outputFile;
my $searchPath;
GetOptions(
'outputFile=s' => \$outputFile,
'searchPath=s' => \$searchPath,
);
die "Usage : perl sample.pl -outputFile -searchPath\n"
unless $outputFile && $searchPath;
die "No such directory found: $searchPath\n" unless -d $searchPath;
find( sub { print "$File::Find::name\n" if /$outputFile/ }, $searchPath );
答案 1 :(得分:1)
#!/usr/bin/perl --
use strict; use warnings;
use Data::Dump qw/ dd /;
use File::Find::Rule qw/ find /;
my @files = find(
file =>
name => '*.xml',
in => \@ARGV
);
dd \@files;
__END__
$ perl ffrule
[]
$ perl ffrule ../soap
[
"../soap/ex1.xml",
"../soap/ex2.xml",
"../soap/ex3.xml",
]