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