added cgi_weather
[spider.git] / Geo / TAF / example / fetch_weather.pl
1 #!/usr/bin/perl -w
2
3 # $Id$
4
5 # this has been taken from Geo::METAR and modified
6 #
7 # Brief Description
8 # =================
9 #
10 # fetch_temp.pl is a program that demonstrates how to get the current
11 # temperature from a nearby (or not) airport using Geo::METAR and the
12 # LWP modules.
13 #
14 # Given an airport site code on the command line, fetch_temp.pl
15 # fetches the current temperature and displays it on the
16 # command-line. For fun, here are some example airports:
17 #
18 # LA     : KLAX
19 # Dallas : KDFW
20 # Detroit: KDTW
21 # Chicago: KMDW
22 #
23 # and of course: EGSH (Norwich)
24 #
25 #
26
27 # Get the site code.
28 my @sort;
29 while ($ARGV[0] =~ /^-/ && @ARGV > 1) {
30         my @f = split //, shift @ARGV;
31         shift @f;
32         foreach $f (@f) {
33                 push @sort, 'taf' if $f eq 't' && ! grep $_ eq 'taf', @sort; 
34                 push @sort, 'staf' if $f eq 's' && ! grep $_ eq 'staf', @sort; 
35                 push @sort, 'metar' if $f eq 'm' && ! grep $_ eq 'metar', @sort; 
36         }
37 }
38 push @sort, 'metar' unless @sort;
39
40 my $site_code = uc shift @ARGV;
41
42 die "Usage: $0 [-mts] <site_code>\n" unless $site_code;
43
44 # Get the modules we need.
45
46 use Geo::TAF;
47 use LWP::UserAgent;
48 use strict;
49
50 my $sort;
51
52 foreach $sort (@sort) {
53
54         my $ua = new LWP::UserAgent;
55
56         my $req = new HTTP::Request GET =>
57                 "http://weather.noaa.gov/cgi-bin/mget$sort.pl?cccc=$site_code";
58         
59         my $response = $ua->request($req);
60         
61         if ($response->is_success) {
62                 
63                 # Yep, get the data and find the METAR.
64                 
65                 my $m = new Geo::TAF;
66                 my $data;
67                 $data = $response->as_string;               # grap response
68                 $data =~ s/\n//go;                          # remove newlines
69                 $data =~ m/($site_code\s\d+Z.*?)</go;       # find the METAR string
70                 my $metar = $1;                             # keep it
71                 
72                 # Sanity check
73                 
74                 if (length($metar)<10) {
75                         die "METAR is too short! Something went wrong.";
76                 }
77                 
78                 # pass the data to the METAR module.
79                 if ($sort =~ /taf$/) {
80                         $m->taf($metar);
81                 } else {
82                         $m->metar($metar);
83                 }
84                 print $m->as_string, "\n";
85                 
86         } else {
87                 
88                 print $response->as_string, "\n";
89                 
90         } 
91         print "\n";
92 }
93
94 exit 0;
95
96