weather.pl


Code Index:

temp

  Report the current temperature for city $city from
  http://m.wund.com/.

#!/usr/bin/perl

use strict;
use warnings;
use Encode;
use LWP::UserAgent;
use MacPerl;

my $city;
my $prog = "This is Weather!";
my $continue = 1;

while ($continue) {
  $city = MacPerl::Ask("${prog}\nEnter city:");
  temp($city);
  $continue = MacPerl::Answer("${prog}\nDo You want to enter another city?",
      "Yes", "No");
}

exit 0;

sub temp {
  my $city = shift;
  my $content;
  my $agent = "LWP";
  my $prog = "This is Weather!";
  my $int_err = "${prog}\nCouldn't get temperature report :(";
  my $inf_err = "${prog}\nThe response was malformed";
  my $empty_err = "${prog}\nThe response was empty";
  my $cnf = "${prog}\nCity $city not found!";
  my $na = "not available";
  my $deg = encode("MacRoman", "°");

  # Create a new useragent
  my $ua = LWP::UserAgent->new();
  $ua->agent($agent);

  # Create a request
  my $req = HTTP::Request->new(
	  POST => 'http://m.wund.com/' .
	  'cgi-bin/findweather/getForecast?brand=mobile&query=' . $city
	  );

  $req->content_type('application/x-www-form-urlencoded');

  # Pass request to the user agent and get a response back
  my $res = $ua->request($req);

  # DEBUG print
  #print $res->content;

  # Check the outcome of the response
  if ($res->is_success) {
    $content = $res->content;
    if ($content =~ /City Not Found/) {
      MacPerl::Answer($cnf);
      return 0;
    }
  }
  else {
    MacPerl::Answer($int_err);
    return 0;
  }

  my $cur_temp = my $windchill = my $sky = $content;
  $cur_temp =~ s/^.+?Temperature.+?<b>(-?\d+)<\/b>&deg;C.+$/$1°C/ms;
  
  if ($windchill =~ /Windchill/) {
    $windchill =~ s/^.+?Windchill.+?<b>(-?\d+)<\/b>&deg;C.+$/$1°C/ms;
  }
  else {
    $windchill = $na;
  }
  
  if ($sky =~ />Conditions</) {
    $sky =~ s/^.+?Conditions.+?<b>([\w\s]+)<\/b>.+$/$1/ms;
  }
  else {
    $sky = $na;
  }
  
  if ($cur_temp =~ /^[\s]$/) {
    MacPerl::Answer("${empty_err}");
    return 0;
  }
  elsif ($cur_temp !~ /^-?\d+°C$/ ||
      ($windchill !~ /^-?\d+°C$/ && $windchill !~ /^$na$/) ||
      ($sky !~ /^[\w\s]+$/ && $sky !~ /^$na$/)
  ) {
    MacPerl::Answer(${inf_err});
    return 0;
  }
  else {
    $cur_temp =~ s/°/$deg/;
    $windchill =~ s/°/$deg/;
    MacPerl::Answer("${prog}\n${city}\nTemperature: ${cur_temp}\n" .
	"Windchill: ${windchill}\n" .
	"Sky: ${sky}");
    return 0;
  }
}