CGI and Perl

Listing 14.2. simpleparse-net.

use URI::URL;
 use HTML::TreeBuilder;
 use LWP::Simple qw(get);
 $base = "";
 $h  = HTML::TreeBuilder->new;
 foreach $pair (@{$h->extract_links(qw<a img>)}) {
     my($link,$elem) = @$pair;
     $url = url($link,$base);
     print $url->abs,"\n";

Running Listing 14.2, with the libwww module properly installed creates the following output, based on the URL

my current ISP, and all of the A and IMG links within that page:
 mailto:[email protected]
 mailto:[email protected]

Note that this listing may vary, depending on your location and whether there have been changes to index.html since this chapter was written. Now that you've seen how to use the LWP modules to do some very simple parsing, let's take a look at how to use them for some useful tasks.

Editing and Verifying HTML

You can use Perl in a number of ways to make changes in and perform verification and validation on HTML. There are modules that handle the parsing and substitutions, as well as several complete tools to check the syntax of the HTML and the validity of the internal anchors to other locations and documents. The following examples demonstrate how to use these tools to perform tasks that may confront you as a Webmaster from time to time. Converting from Absolute to Relative URLs Suppose that at some point, when the Webmaster is coming up to speed on the HTML specifications, he or she creates a document that uses the complete form of the URL in all links, giving the scheme, host, and path. Later, as understanding grows, the Webmaster wishes to go back and change all the links in the HTML documents that correspond to local resources to have the relative form. This way, if any site is mirroring his/her site, requests for local documents from the mirror copy will be served from the mirror site instead of the master site.

In order to accomplish this task, you'll need to start with the script that parses URLs generally, shown in Listing 14.2. Then you'll add the capability (see Listing 14.3) to print out the new HTML file with the links changed to relative form when they refer to local resources.