ЭЛЕКТРОННАЯ БИБЛИОТЕКА КОАПП |
Сборники Художественной, Технической, Справочной, Английской, Нормативной, Исторической, и др. литературы. |
20.8. Finding Fresh LinksProblemGiven a list of URLs, you want to determine which have been most recently modified. SolutionThe program in Example 20.6 reads URLs from standard input, rearranges by date, and prints them back to standard output with those dates prepended. Example 20.6: surl#!/usr/bin/perl -w # surl - sort URLs by their last modification date use LWP::UserAgent; use HTTP::Request; use URI::URL qw(url); my($url, %Date); my $ua = LWP::UserAgent->new(); while ( $url = url(scalar <>) ) { my $ans; next unless $url->scheme =~ /^(file|https?)$/; $ans = $ua->request(HTTP::Request->new("HEAD", $url)); if ($ans->is_success) { $Date{$url} = $ans->last_modified || 0; # unknown } else { print STDERR "$url: Error [", $ans->code, "] ", $ans->message, "!\n"; } } foreach $url ( sort { $Date{$b} <=> $Date{$a} } keys %Date ) { printf "%-25s %s\n", $Date{$url} ? (scalar localtime $Date{$url}) : "<NONE SPECIFIED>", $url; } DiscussionThe surl script works more like a traditional filter program. It reads from standard input one URL per line. (Actually, it reads from < Here's an example of using the xurl program from the earlier recipe to extract the URLs, then running that program's output to feed into surl. % xurl http://www.perl.com/ | surl | head Having a variety of small programs that each do one thing and that can be combined into more powerful constructs is the hallmark of good programming. You could even argue that xurl should work on files, and that some other program should actually fetch the URL's contents over the Web to feed into xurl, churl, or surl. That program would probably be called gurl, except that a program by that name already exists: the LWP module suite has a program called lwp-request with aliases HEAD, GET, and POST to run those operations in shell scripts. See AlsoThe documentation for the CPAN modules LWP::UserAgent, HTTP::Request, and URI::URL; Recipe 20.7 |