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.

CHAPTER 9 ■ XML PARSING WITH PERL 171The code reads in the XML with the forcearray option enabled. Each value is then accessedthrough its dereferenced array index. The exception is the element, which may be multivalued.The element is printed by using an array reference <strong>to</strong> that specific element.Since four of the five elements in this XML data structure can have only one value, youmay want <strong>to</strong> specify which elements should go in<strong>to</strong> an array, instead of rolling every elementin<strong>to</strong> an array. Instead of merely accepting 1 for enabled and 0 for disabled, the forcearrayoption can accept a comma-separated list of elements that should be rolled in<strong>to</strong> an array.Continuing with the previous example, using forcearray just for the elementlooks like this:#!/usr/bin/perluse strict;use XML::Simple;my $xml = XMLin('./xml_example2',forcearray=> [ 'vehicle' ]);foreach my $cus<strong>to</strong>mer (@{$xml->{cus<strong>to</strong>mer}}) {print "Name: $cus<strong>to</strong>mer->{first_name} ";print "$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";print "Vehicle(s): @{$cus<strong>to</strong>mer->{vehicle}}\n";}Notice in this example that the array index ->[0] is now gone for the original four elements,since those are no longer rolled in<strong>to</strong> an array by XML::Simple.KeyAttrThe KeyAttr option is used <strong>to</strong> control how elements are rolled in<strong>to</strong> arrays and hashes. Recallan earlier example showing an XML structure as displayed with Data::Dumper. Changing thekey attribute <strong>to</strong> be the element reveals this output:$VAR1 = {'cus<strong>to</strong>mer' => {'frank@example.com' => {'dob' => '3/10','first_name' => 'Frank','last_name' => 'Sanbeans'},'sandy@example.com' => {'dob' => '4/15','first_name' => 'Sandy','last_name' => 'Sanbeans'}}};

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

Saved successfully!

Ooh no, something went wrong!