0

I'm trying to parse multiple xml files but i'm a bit stuck with something. The $twig->parsefile("output_1.xml"); section of the below script works fine in parsing the file stated. However, I would like to parse all of the .xml files in the direcotry. I have tried writing each file into the code like so:

$twig->parsefile("output_1.xml" "output_2.xml" "output_3.xml");

And i've also tried using a wildcard like I would in bash like so :

$twig->parsefile("*.xml");

But none of these attempts work. How can I change the script so that all of the .xml files in the directory are parsed by the script? I apologise for my lack of knowledge, i've only just started using Perl.

#!/bin/perl -w

use strict;
use XML::Twig;

my $twig = XML::Twig->new(
   twig_handlers => {item => \&acct}
);
$twig->parsefile("output_1.xml");                              

sub acct {
    my ($t, $elt) = @_;

          for my $tag (qw(itemId title viewItemURL convertedCurrentPrice)) {
                    print $elt->field($tag), "\n";
                        }
                            print "\n";
                            print "\n";
                            }
2

You can enumerate the directory contents as follows:

my @files = <*.xml>;    # or: my @files = </your/path/to/*.xml>;
foreach my $file (@files) {
    $twig->parsefile($file);
}
2
  • HI thanks, for the response. I tried this and i'm getting the following errors........ Global symbol "@files" requires explicit package name at testscript.pl line 10. Global symbol "$file" requires explicit package name at testscript.pl line 11. Global symbol "@files" requires explicit package name at testscript.pl line 11. Global symbol "$file" requires explicit package name at testscript.pl line 12. Execution of testscript.pl aborted due to compilation errors.
    – neilH
    Apr 21 '16 at 20:53
  • @bms9nmh I've added "my" declarations to prevent these errors. See updated answer.
    – Guido
    Apr 21 '16 at 22:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.