Home > Mobile >  How to create a XML by Perl?
How to create a XML by Perl?

Time:07-14

I'm new Perl and Trying to make a xml document. I came across an article from How can I create XML from Perl?

#!/usr/bin/env perl

#
# Create a simple XML document
#

use strict;
use warnings;
use XML::LibXML;

my $doc = XML::LibXML::Document->new('1.0', 'utf-8');

my $root = $doc->createElement('my-root-element');
$root->setAttribute('some-attr'=> 'some-value');

my %elements = (
    color => 'blue',
    metal => 'steel',
);

for my $name (keys %elements) {
    my $element = $doc->createElement($name);
    my $value = $elements{$name};
    $tag->appendTextNode($value);
    $root->appendChild($element);
}

$doc->setDocumentElement($root);
print $doc->toString();

I expected that the output as below

<?xml version="1.0" encoding="utf-8"?>
<my-root-element some-attr="some-value">
    <color>blue</color>
    <metal>steel</metal>
</my-root-element>

but I got the result as below

% perl test2.pl
Global symbol "$tag" requires explicit package name at test2.pl line 18.
Execution of test2.pl aborted due to compilation errors.

Could you guide me please How do I resolve this problem?

CodePudding user response:

That's not one of Perl's clearest error messages. But it has improved in recent versions of Perl. Running your code using Perl 5.34.1, I get this, which is far more helpful:

Global symbol "$tag" requires explicit package name (did you forget to declare "my $tag"?)

That would, I hope, enable you to investigate the problem and find the error.

If that doesn't help, then the standard advice when you find a Perl error that you don't understand is to add use diagnostics to your code. That would have should you this expanded error:

(F) You've said "use strict" or "use strict vars", which indicates that all variables must either be lexically scoped (using "my" or "state"), declared beforehand using "our", or explicitly qualified to say which package the global variable is in (using "::").

The "(F)" at the start means it's a fatal error. But the rest of it explains the problem pretty well.

I expect that this error would have enabled you to work out what the problem was.

  •  Tags:  
  • perl
  • Related