R
Richard Lawrence
Hi there,
Consider the following XML in a file called "data.xml":
<user>
<name>Frank</name>
<age>27</age>
<friends>
<friend>
<name>Sue</name>
<location>London</location>
</friend>
<friend>
<name>Jane</name>
<location>Paris</location>
</friend>
</friends>
</user>
If I use the following:
#!/usr/bin/perl -w
use strict;
use XML::Simple;
my $user = XMLin("data.xml");
print "Hi, my name is " . $user->{name};
print " and I am " . $user->{age} . " years old. ";
print "My friends are ";
# Begin horrible code
my ($key, $value, $k, $v);
while(($key, $value) = each %{$user->{friends}})
{
while(($k, $v) = each %{$value})
{
print "$k (who lives in " . $v->{location} . ") and ";
}
}
# End horrible code
print "thats it!\n";
then I get the intended:
Hi, my name is Frank and I am 27 years old. My friends are Sue (who
lives in London) and Jane (who lives in Paris) and thats it!
which is great.
However as you have probably noticed from the code, the whole $key,
$value, $k, $v and nested while's looks really horrible to me and I'm
sure there is a far better way to do this.
Can anyone advise on the best way to re-write this section whilst still
maintaining readability?
Many thanks in advance,
Richard.
Consider the following XML in a file called "data.xml":
<user>
<name>Frank</name>
<age>27</age>
<friends>
<friend>
<name>Sue</name>
<location>London</location>
</friend>
<friend>
<name>Jane</name>
<location>Paris</location>
</friend>
</friends>
</user>
If I use the following:
#!/usr/bin/perl -w
use strict;
use XML::Simple;
my $user = XMLin("data.xml");
print "Hi, my name is " . $user->{name};
print " and I am " . $user->{age} . " years old. ";
print "My friends are ";
# Begin horrible code
my ($key, $value, $k, $v);
while(($key, $value) = each %{$user->{friends}})
{
while(($k, $v) = each %{$value})
{
print "$k (who lives in " . $v->{location} . ") and ";
}
}
# End horrible code
print "thats it!\n";
then I get the intended:
Hi, my name is Frank and I am 27 years old. My friends are Sue (who
lives in London) and Jane (who lives in Paris) and thats it!
which is great.
However as you have probably noticed from the code, the whole $key,
$value, $k, $v and nested while's looks really horrible to me and I'm
sure there is a far better way to do this.
Can anyone advise on the best way to re-write this section whilst still
maintaining readability?
Many thanks in advance,
Richard.