Simply, LWP::Simple
August 9, 1999
The LWP::Simple module, being simpleminded as it is, basically
only knows how to do one thing: retrieve a web page. A perfect
match for us, since we only need to retrieve a web page --
more specifically, a web page that contains the current
temperature in Smallville! First, we must be sure to include
the LWP::Simple module at the top of the Perl script:
Including LWP::Simple at the start of our new
weather-aware smallville.cgi.
#!/usr/bin/perl
use CGI;
use LWP::Simple;
...etc...
|
There are probably many web sites that offer the current
temperature, but we've chosen to use the
Weather Underground
site provided by the University of Michigan since it offers
national and international weather conditions. In fact, it's
easy to construct a URL which provides current weather for
any ZIP code at the Weather Underground: (note: this long
URL is line wrapped in this article on several occasions
only to improve onscreen formatting.)
http://www.wunderground.com/
cgi-bin/findweather/getForecast?query=ZIPCODE
So, assuming that Smallville resides in the ZIP code 14850,
we can use LWP::Simple in our Perl script to retrieve the
weather report page from the Weather Underground. The entire
page is retrieved into the variable $weatherPage.
Retrieving the Weather Underground web page into a
local variable.
#set URL to weather web page
$weatherURL="http://www.wunderground.com/cgi-bin/
findweather/getForecast?query=14850";
#retrieve this web page
$weatherPage=get($weatherURL);
|
The web page returned from this URL is actually rather large
with lots of information. How can we easily pick out only the
temperature? There is no golden rule -- in brief, web pages
contain data marked with structure but not meaning -- thus
there is no surefire way for a Perl script, for instance, to
look at the HTML of a page and say "a-ha! here is the
temperature". Speaking tangentially, this is the great
allure of
XML which, among
other things, could solve this problem easily by allowing a
developer to mark the meaning of data in a document. XML
aside, though, we need a solution -- fortunately, the Weather
Underground provides a convenient one. If you look at the
HTML produced from the Weather Underground you find a series
of HTML comments which contain the basic weather conditions:
<!-- Condition == -->
<!-- Temperature == 20.0 -->
A Simple Goal
The Perl You Need to Know
Grasping for Tags
|