I am trying to implement a procedure that iterates over all the subdirectories from a root directory, looking for .xml files in 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();
I’m not very familiar with Perl. The sub iterateDir procedure is supposed to iterate over a the sub-directories, while the getXMLFiles would filter for .xml files, returning them. I would use those .xml files for parsing. That’s why I’m trying to find all the .xml files from a root directory.
However, I don’t know how can I use the sub wanted procedure inside iterateDir to send the dirpath to getXMLFiles. How could I accomplish that?
$File::Find::diris the current directory name. You can use that variable in thewantedsub and pass it to subs you call. See the docs for more info on the wanted functionThis should work: