views:

524

answers:

2

I'm using cURL to get the XML file for my Twitter friend's timeline. (API here.)

Currently (though I'd be open for more suggestions) I am using Perl to parse the XML. This is my first time using Perl and I really don't know what I am doing. Currently this is my code:

#!/usr/bin/perl
# use module
use XML::Simple;
use Data::Dumper;
# Create object.
$xml = new XML::Simple;
# Read XML file.
$data = $xml->XMLin("/tmp/data.xml");
# Print output.
print Dumper($data);

Now I want to go through the XML and print out each person's name and then what they tweeted. Currently I have not found a good guide on Perl's foreach loop when there is a complicated data structure like this one.

How can I achieve this?

(Any other ways to parse the XML in a terminal friendly environment would be nice to know about as well)

+4  A: 

There's no generic answer - it depends on the content of your data.xml. For the example on the page you can do the following:

foreach my $unode ( values %{$data->{status}} ) {
  print "$unode->{user}->{name} \t $unode->{created_at} \t $unode->{text} \n";
}

output:

Doug Williams    Tue Apr 07 22:52:51 +0000 2009          At least I can get your humor through tweets. RT @abdur: I don't mean this in a bad way, but genetically speaking your a cul-de-sac.

What it does is - it gets the hashref called 'status', dereferences it, and then iterates through its values, which are hashrefs too, assigning each of them to $unode.

You can also look at print Dumper $unode to see what else is available there. Also note that XML::Simple can be a little tricky in how it parses xml - sometimes you may need to pass in extra parameters to make it create arrays where you want it to - check out the docs

Programming Perl Chapter 9 gives you an introduction of the different nested data structures in perl.

If you follow the link to the API it is there.
Eric Koslow
ok, just saw it and updated
@Naumcho: Don't post links to pirated books.@Eric: See `perldoc perldsc` for a good discussion of complex data structures in Perl.
Telemachus
@Telemachus - didn't realize it was pirated - thanks
+12  A: 

Why not use the Net::Twitter API on CPAN?

seth
I was about to ask that. :-)
Alan Haggai Alavi