The Code
Instead of parsing the XML by hand with XML::Simple (as in most of the Perl hacks in this book), this script uses a module tailor-made for working with RSS called, appropriately enough, XML::RSS. This module features some handy shortcuts when parsing RSS, and it makes working with the format even easier. To install XML::RSS on your system, you can use CPAN from the command line like this:
Figure 1. A Yahoo Groups! RSS feed
perl –MCPAN –e shell
cpan> install XML::RSS
The other module you'll need is LWP::Simple, which will fetch the RSS from Yahoo!.
Save the following code to a file called write_feed.pl:
#!/usr/bin/perl
# write_feed.pl
# Accepts an RSS feed URL and prints as HTML.
# Usage: write_feed.pl <RSS Feed URL>
use LWP::Simple;
use XML::RSS;
# Grab the incoming feed URL
my $url = join(' ', @ARGV) or die "Usage: write_feed.pl <RSS Feed URL>\n";
# Make the request
my $rss = get($url);
# Parse the RSS
my $xmlrss = new XML::RSS();
$xmlrss->parse($rss);
# Print the feed Header with title
print "<h3>" . $xmlrss->channel('title') . "</h3>";
print "<ul>";
# Loop through the items returned, printing them out
foreach my $item (@{$xmlrss->{'items'}}) {
my $title = $item->{'title'};
my $url = $item->{'link'};
my $description = $item->{'description'};
print "<li><a href=\"$url\">$title</a></li>\n";
}
# Print the feed Footer
print "</ul>";
The XML::RSS parse() function turns the RSS from Yahoo! into an object that Perl can work with. From there, the final foreach loops over each item in the feed and prints the results with a bit of HTML formatting.