A simply and cool script for the weather forecast. May be even correct
.. thanks to Weather::Underground perl module
PERL:
#!/usr/bin/perl
use Weather::Underground;
May be I'll use it from the web too, therefore I'd like to check how the script was called to get it params:
PERL:
if(defined $ENV{'QUERY_STRING'}) { # check if we are called from the browser
print "Content-Type: text/html\n\n";
@data = split(/&/, $ENV{'QUERY_STRING'});
$location = @data[0];
$html_out = 1;
} elsif(defined $ARGV[0]) { #check if we are called from the command line
$location = $ARGV[0] . " " . $ARGV[1];
$html_out = 0;
} else {
print "No location given!\n";
exit 1;
}
Now lets see if the given location is valid:
PERL:
$weather = Weather::Underground->new( place => $location,
debug => 0);
$array_ref = $weather->get_weather($location);
if(!$array_ref) {
print "Can't find location $location\n";
exit 1;
}
And the next step is simply to output (accordingly to the request type)
PERL:
if ($array_ref) {
if($html_out) {
print "<table>";
foreach $place (@{$array_ref}) {
foreach $key (keys %{$place}) {
$value = $place->{$key};
print "<tr><td>$key</td><td>$value</td></tr>\n";
}
}
print "</table>";
} else {
foreach $place (@{$array_ref}) {
foreach $key (keys %{$place}) {
$value = $place->{$key};
print "$key - $value\n";
}
}
}
}
exit 0;
Now call it like this in the console
BASH:
user@host:~$ weather Muenchen Germany
or place it on your host and just call it within a browser:
CODE:
http://yourhost.com/cgi-bin/weather?Warsaw, Poland
The only one thing is here for me a pity, namely - the ambiguous localization. For example "Muenchen, Germany" should be either "Munich, Germany" or "München, Deutschland" (or "Muenchen, Deutschland"). As for the rest it's cool
