10.07.2015 Views

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

Beginning Web Development With Perl : From Novice to ... - Nabo

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

168CHAPTER 9 ■ XML PARSING WITH PERLThe code shown uses the forcearray option, which isn’t really necessary. The XML beingparsed in this example consists of solely single values—each cus<strong>to</strong>mer record has one andonly one value for date of birth, e-mail address, and so on. Another method <strong>to</strong> parse this particularXML looks like this:#!/usr/bin/perluse strict;use XML::Simple;my $xml = XMLin('./example1.xml');foreach my $cus<strong>to</strong>mer (@{$xml->{cus<strong>to</strong>mer}}) {print "Name: $cus<strong>to</strong>mer->{first_name} $cus<strong>to</strong>mer->{last_name}\n";print "Birthday: $cus<strong>to</strong>mer->{dob}\n";print "E-mail Address: $cus<strong>to</strong>mer->{email}\n";}The difference between this and the previously shown code is subtle. Missing from thisexample is the reference <strong>to</strong> the first element in the array ->[0]. When parsing XML with multivaluedelements, accessing those elements with forcearray makes access <strong>to</strong> the elementsmuch easier, as you’ll see a bit later in the “XML::Simple Options” section.Data::DumperAn even simpler, though arguably less useful method, for parsing an XML file with XML::Simple is<strong>to</strong> use Data::Dumper. You can use the Data::Dumper module <strong>to</strong> quickly print out the XML as it isbeing read and processed by the XMLin() subroutine. Doing so helps during debugging and inother cases, such as working with databases. Rather than using the foreach loop in the previousexample, you could use Data::Dumper <strong>to</strong> print the contents of the XML, as shown in this example:#!/usr/bin/perluse strict;use XML::Simple;use Data::Dumper;my $xml = XMLin('./example1.xml',forcearray => 1);print Dumper($xml);Compare the output from the earlier example with the output from the Data::Dumper versionof the program:$VAR1 = {'cus<strong>to</strong>mer' => [{'email' => ['frank@example.com'],

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!