74 Part I — Basics
Generating XML
You can generate XML very easily just by embedding data into suitable tags when you write
out the information. Listing 5-9 shows an adaptation of the fixed record length parsing code
that outputs the information from a fixed-width record file into XML.Listing 5-9:Generating XML from Fixed Dataopen(DATA,$ARGV[0]) or die “Cannot open file: $!”;my $reclength = 10+10+20+20+20;my $record;print ‘<staff>’;while(read(DATA,$record,$reclength))
{
my ($id,$ref,$fname,$lname,$country) = unpack(‘a10a10a20a20a20’,$record);$id = int($id);
$ref = int($ref);$fname = despace($fname);
$lname = despace($lname);
$country = despace($country);print <<EOF;
<staffmember>
<td>$id</id>
<ref>$ref</ref>
<firstname>$fname</firstname>
<lastname>$lname</lastname>
<country>$country</country>
</staffmember>
EOF}close(DATA);print ‘</staff>’;sub despace
{
my ($text) = @_;$text =~ s/ *$//g;return $text;
}