pawelb has asked for the wisdom of the Perl Monks concerning the following question:

Hello all of You, as I'm quite new to Perl, I am trying to get into XML parsing using XML::LibXML module. So far, I have read my file as well as I could extract some data I was interested in. My piece of code that makes that happen:
#!/usr/bin/perl use strict; use warnings; use XML::LibXML; my $source = shift @ARGV; my $prsr = XML::LibXML->new(); $prsr->keep_blanks(0); my $doc = $prsr->parse_file($source); my $top = $doc->getDocumentElement; my @licenses = $top->getElementsByTagName('feature'); foreach my $attrib (@licenses) { my $name = $attrib->getAttribute('name'); my $count = $attrib->getAttribute('count'); print $name,":",$count,"\n"; }
I can say that LibXML has a lot potential, but somehow I do not get how I can write my variable data into external file, for example: output.txt using this very module. Please, at least point where should I look for an answer. Thank You in advance!

Replies are listed 'Best First'.
Re: XML::LibXML save variable data to a file
by toolic (Bishop) on Jan 19, 2015 at 15:26 UTC
    To create an output file, use open and print to a filehandle:
    open my $fh, '>', 'output.txt' or die "cannot open output.txt: $!"; foreach my $attrib (@licenses) { my $name = $attrib->getAttribute('name'); my $count = $attrib->getAttribute('count'); print $fh "$name:$count\n"; }
Re: XML::LibXML save variable data to a file
by Anonymous Monk on Jan 19, 2015 at 15:25 UTC

    What exactly do you want to have appear in the output file - the XML, or the output of your print? For the former, see toFile in XML::LibXML::Document, so e.g. $doc->toFile("output.xml",1);. For the latter, there is some example code for opening and printing to files in perlintro.