|
Posted by Tad J McClellan on June 9, 2008, 11:10 pm
Please log in for more thread options
> Recently I have started using XML in other areas and realize that this
> format would be more easily maintained then the text files. So the
> question of the day, can someone point me to some simple XML
^^^^^^^^^^
^^^^^^^^^^
Errr, like the XML::Simple module?
> implementation in perl that wont take days to learn and includes some
> commentary on how it works that is geared more to the layman?
You will need to understand Perl's references and data structures
to use XML::Simple, start with perlreftut.pod.
> As a more detailed example of what I am hoping to accomplish, say I
> have a simple tab delimited record in a file that contains a persons
> address:
>
> First Name\tLast Name\tStreet Address\tCity\tState\t\Zip
>
> and I wanted to get all the zip codes in this file I would load:
>
> open(FILE,"thefile.txt");
> @data = <FILE>;
> close(FILE);
>
> foreach $record (@data)
> {
> @temp = split("\t",$record);
> $zips[@zips] = $temp[5];
> }
>
> Now if I decided later to have 2 street addresses and a middle name
> the above code would have to be altered. But I was thinking if it was
> in XML and each entry looked like this:
>
><record firstname="John" lastname="Doe" address="123 Main"
> city="Anytown" state="NN" zip="12345" />
You could also represent the "fields" in elements rather than
in attributes (as I've done below).
See the XML FAQ:
http://xml.silmaril.ie/developers/attributes/
> and the psuedo code would be something like
>
> open xml file
> get number of records (elements)
> for each record
> load record
> $zips[@zips] = value of attribute named "zip"
> next record
>
> This would allow the XML file to be changed, more information added
> etc without changing the code.
I fail to see how switching to an XML representation would
obviate the need to change the code though...
> I know one of your are going to tell me what module to include - thats
> fine, just hopefully it includes a good description.
----------------------------
#!/usr/bin/perl
use warnings;
use strict;
use XML::Simple;
my $xml = join '', <DATA>; # No Uri, I don't want to use File::Slurp here :-)
my $ref = XMLin($xml);
foreach my $person ( @{ $ref-> } ) { # "Use Rule 1" from perlreftut
print "$person->\n";
}
__DATA__
<?xml version='1.0' encoding='UTF-8'?>
<addressbook>
<person>
<firstname>John</firstname>
<lastname>Doe</lastname>
<address>123 Main</address>
<city>Anytown</city>
<state>NN</state>
<zip>12345</zip>
</person>
<person>
<firstname>Bill</firstname>
<lastname>Aitch</lastname>
<city>Dunno</city>
<state>Confusion</state>
<zip>67890</zip>
</person>
</addressbook>
----------------------------
--
Tad McClellan
email: perl -le "print scalar reverse qq/moc.noitatibaher0cmdat/"
|