A Slide-Show Presentation via SVG - Part 1 of Chapter 7 from Perl Graphics Programming (2/4) | WebReference

A Slide-Show Presentation via SVG - Part 1 of Chapter 7 from Perl Graphics Programming (2/4)

To page 1current pageTo page 3To page 4
[previous] [next]

Perl Graphics Programming, Chapter 7: Creating SVG with Perl

There are several ways of transforming XML files from one format to another. An XML purist would try to use the XSLT transformation language to write a set of rules for rearranging the input XML tree into an output tree. In this chapter, we'll try a different method: translating the input file into an intermediate data structure (in this case, a big hash).

This simple example uses the XML::Simple module for the parsing of the file. This module provides all of two functions for reading and writing XML (XMLin and XMLout). A more robust application may want to use one of the other fine modules available on CPAN for XML parsing.

XML::Simple reads the previously described XML document into a hash where each of the keys is a tag name. If an element has a child, that child is represented as an anonymous hash. If there are several children, they are grouped together as an anonymous array of hashes.

Our script iterates through the elements of the hash and, with the help of the XML::Writer module (a basic XML library for writing simple tags), generates one SVG file for each <slide> element.

Each slide actually consists of two <svg> elements, one top-level graphic and one that encapsulates the textual area. This structure allows the text to be drawn in one pass and scaled to fit the dimensions of the top-level graphic.

The code for the slide generator is shown in the following example. First it creates a new simple XML parser. XML::Simple only implements two functions: XMLin and XMLout. Calling XMLin creates a hash representing the XML tree.

If an element has more than one child of the same type, they are stored in an anonymous array. If there's only one child of a particular type, it appears as a hash reference. For this reason, we use a subroutine called dereference( ) that sorts out the data type of the child and always returns a dereferenced array.

#!/usr/bin/perl -w
   
# SVG presentations
   
use strict;
use XML::Simple;    # Used to parse the XML input
use XML::Writer;    # Used to write the SVG output
use IO::Scalar;     # Allows you to easily redirect
                    # output from a filehandle to a scalar
my $height = 400;
my $width = 600;
my $titlesize = 36;
   
my $parser = new XML::Simple(  );
my $slideshow = $parser->XMLin($ARGV[0]); 
my @slides = dereference($slideshow->{'slide'});

To page 1current pageTo page 3To page 4
[previous] [next]

Created: February 12, 2003
Revised: February 12, 2003

URL: https://webreference.com/programming/perl/chap7/1/2.html