I am working on a perl script which takes as input path to directory in linux. Directory has xml files in it. Perl script iterates through all the xml files and convert each xml file into json format.
I have my code written and working properly but i am stuck at validation conditions in perl.
#!/usr/bin/perl
use JSON;
use XML::Simple;
use File::Spec;
$num_args = $#ARGV + 1;
if ($num_args != 1) {
print "\nUsage: $0 <input directory>\n";
exit;
}
my $dirPath = $ARGV[0];
if (not -e $dirPath)
{
$dirPath = "/opt/poll/";
}
opendir(DIR, $dirPath);
my @docs = grep(/\.xml$/,readdir(DIR));
foreach my $file (@docs)
{
my $abs_path = join("",$dir,$file);
my $json_object = xml2json($abs_path);
print_json($json_object);
}
sub print_json
{
my $json_object = $_[0];
print $json_object;
}
sub xml2json
{
my $filename = $_[0];
#print $filename;:q!
#print "\n";
# Create the object of XML Simple
my $xmlSimple = new XML::Simple(KeepRoot => 1);
# Load the xml file in object
my $dataXML = $xmlSimple->XMLin($filename);
# use encode json function to convert xml object in json.
my $jsonString = encode_json($dataXML);
#print $jsonString;
return $jsonString;
}
few validation i am planning to test the corner cases:
1> opendir(DIR, $dirPath); : if opendir fails to open the directory how to handle this case
2> How to check that the xml files exists and can be read first. Otheriwse the XMLSimple constructor could throw an unhandled exception.
3> How to handle condition when input xml file is empty or input xml file is corrupt.
4> What if $dataXML is undef?
I am new to perl so having troubles reading through its documentation and get the solution. Though i was able to wrote the whole script.
Let me know if any suggestions. I tried using eval here in above cases but not sure how to use it.
Thanks in advance.
No comments:
Post a Comment