b88aa299de128ccc2e9e20f3591b4d3d84e48a4f
[spider.git] / Geo / TAF / example / fetch_metar.pl
1 #!/usr/bin/perl -w
2
3 # $Id$
4
5 # this has been taken from Geo::METAR
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 # Get the site code.
27
28 my $site_code = uc shift @ARGV;
29
30 die "Usage: $0 <site_code>\n" unless $site_code;
31
32 # Get the modules we need.
33
34 use Geo::TAF;
35 use LWP::UserAgent;
36 use strict;
37
38 my $ua = new LWP::UserAgent;
39
40 my $req = new HTTP::Request GET =>
41   "http://weather.noaa.gov/cgi-bin/mgetmetar.pl?cccc=$site_code";
42
43 my $response = $ua->request($req);
44
45 if (!$response->is_success) {
46
47     print $response->error_as_HTML;
48     my $err_msg = $response->error_as_HTML;
49     warn "$err_msg\n\n";
50     die "$!";
51
52 } else {
53
54     # Yep, get the data and find the METAR.
55
56     my $m = new Geo::TAF;
57     my $data;
58     $data = $response->as_string;               # grap response
59     $data =~ s/\n//go;                          # remove newlines
60     $data =~ m/($site_code\s\d+Z.*?)</go;       # find the METAR string
61     my $metar = $1;                             # keep it
62
63     # Sanity check
64
65     if (length($metar)<10) {
66         die "METAR is too short! Something went wrong.";
67     }
68
69     # pass the data to the METAR module.
70     $m->metar($metar);
71
72     print $m->as_string, "\n";
73
74 } # end else
75
76 exit;
77
78 __END__
79
80