Generating XML

You should generate XML programmatically whenever possible to help ensure well-formedness. In Perl, the XML::Writer module lets us do this.

XML::Writer is very easy to use. An example based on the one from the perldoc:

use XML::Writer;
use IO::File;
use strict;

my $output = new IO::File(">output.xml");

my $writer = new XML::Writer(OUTPUT => $output);
$writer->xmlDecl("UTF-8");
$writer->startTag("greeting", 
                  "class" => "simple");
$writer->characters("Hello, world!");
$writer->endTag("greeting");
$writer->end();
$output->close();

Let's go through the example line by line:

use XML::Writer;
use IO::File;
This just lets perl know we want to use the XML::Writer and IO::File modules.
my $output = new IO::File(">output.xml");
The IO::File module provides an object-oriented wrapper around perl filehandles. We can use $output in exactly the same way as if we did open(OUTPUT,">$output.xml"), except that we can pass $output around directly instead of having to resort to things like \*OUTPUT.
my $writer = new XML::Writer(OUTPUT => $output);
This creates a new XML::Writer object with output directed to the filehandle $output. To write to standard output, leave off the OUTPUT option. To write to a string, we can just pass a reference to a string to the IO::Handle constructor (this requires perl 5.8 or later, for earlier versions you can use IO::String):
my $string = "";
my $output = new IO::File(\$string);
my $writer = new XML::Writer(OUTPUT => $output);

# ... do some stuff with $writer ...

print $string;
Going back to our example, we next insert an an XML declaration:
$writer->xmlDecl("UTF-8");
The "arrow notation" is perl's method of calling methods on objects. The declaration that $writer->xmlDecl emits lets us know that the output is XML and uses utf-8 as the character set. We'll talk more about character sets and encodings later. The output from this is
<?xml version="1.0" encoding="UTF-8"?>
Then we open a <greeting> tag with the attribute class = "simple", write the characters Hello, world! and finally close the <greeting> tag.
$writer->startTag("greeting", 
                  "class" => "simple");
$writer->characters("Hello, world!");
$writer->endTag("greeting");
This produces
<greeting class="simple">Hello, world!</greeting>

Then we clean up by telling $writer we're done writing so that it can make sure we didn't leave any elements open and by closing our output filehandle.

$writer->end();
$output->close();