Редакция 3 | К новейшей редакции | Содержимое файла | Сравнить с предыдущей | Последнее изменение | Открыть журнал | RSS
Редакция | Автор | № строки | Строка |
---|---|---|---|
3 | alex-w | 1 | #!/usr/bin/perl -w |
2 | |||
3 | # $Id: fetch_temp.pl,v 1.1 2007/11/13 21:19:27 koos Exp $ |
||
4 | |||
5 | # Brief Description |
||
6 | # ================= |
||
7 | # |
||
8 | # fetch_temp.pl is a program that demonstrates how to get the current |
||
9 | # temperature from a nearby (or not) airport using Geo::METAR and the |
||
10 | # LWP modules. |
||
11 | # |
||
12 | # Given an airport site code on the command line, fetch_temp.pl |
||
13 | # fetches the current temperature and displays it on the |
||
14 | # command-line. For fun, here are some example airports: |
||
15 | # |
||
16 | # LA : KLAX |
||
17 | # Dallas : KDFW |
||
18 | # Detroit: KDTW |
||
19 | # Chicago: KMDW |
||
20 | |||
21 | # Get the site code. |
||
22 | |||
23 | my $site_code = shift @ARGV; |
||
24 | |||
25 | die "Usage: $0 <site_code>\n" unless $site_code; |
||
26 | |||
27 | # Get the modules we need. |
||
28 | |||
29 | use Geo::ModMETAR; |
||
30 | use LWP::UserAgent; |
||
31 | use strict; |
||
32 | |||
33 | my $ua = new LWP::UserAgent; |
||
34 | |||
35 | my $req = new HTTP::Request GET => |
||
36 | "http://weather.noaa.gov/cgi-bin/mgetmetar.pl?cccc=$site_code"; |
||
37 | |||
38 | my $response = $ua->request($req); |
||
39 | |||
40 | if (!$response->is_success) { |
||
41 | |||
42 | print $response->error_as_HTML; |
||
43 | my $err_msg = $response->error_as_HTML; |
||
44 | warn "$err_msg\n\n"; |
||
45 | die "$!"; |
||
46 | |||
47 | } else { |
||
48 | |||
49 | # Yep, get the data and find the METAR. |
||
50 | |||
51 | my $m = new Geo::ModMETAR; |
||
52 | my $data; |
||
53 | $data = $response->as_string; # grap response |
||
54 | $data =~ s/\n//go; # remove newlines |
||
55 | $data =~ m/($site_code\s\d+Z.*?)</go; # find the METAR string |
||
56 | my $metar = $1; # keep it |
||
57 | |||
58 | # Sanity check |
||
59 | |||
60 | if (length($metar)<10) { |
||
61 | die "METAR is too short! Something went wrong."; |
||
62 | } |
||
63 | |||
64 | # pass the data to the METAR module. |
||
65 | $m->metar($metar); |
||
66 | |||
67 | # ask for the temperature(s) |
||
68 | my $f_temp = $m->TEMP_F; |
||
69 | my $c_temp = $m->TEMP_C; |
||
70 | |||
71 | my $time = localtime(time); |
||
72 | print "The temperature at $site_code is $f_temp F ($c_temp C) as of $time.\n"; |
||
73 | |||
74 | } # end else |
||
75 | |||
76 | exit; |
||
77 | |||
78 | __END__ |
||
79 | |||
80 |