temp.pl


Code Index:

temp

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

#!/usr/bin/env perl

use strict;
use warnings;
use LWP::UserAgent;

print "$0: Usage: $0 city [city] ... [city]\n" and exit 1 if ($#ARGV == -1);

for (@ARGV) {
  temp($_);
}

sub temp {
  my $city = shift;
  my $content;
  my $agent = "LWP";
  my $int_err = "Couldn't get temperature report :(\n";
  my $inf_err = "The response was malformed";
  my $empty_err = "The response was empty";
  my $na = "not available";

  # 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;
  }
  else {
	print $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]$/) {
	print "${empty_err}\n";
	return 0;
  }
  elsif ($cur_temp !~ /^-?\d+°C$/ ||
		 ($windchill !~ /^-?\d+°C$/ && $windchill !~ /^$na$/) ||
		 ($sky !~ /^[\w\s]+$/ && $sky !~ /^$na$/)
		) {
	print "${inf_err}\n";
	return 0;
  }
  else {
    print "${city}\nTemperature: ${cur_temp}\n";
	print "Windchill: ${windchill}\n";
	print "Sky: ${sky}\n";
	print "\n";
    return 1;
  }
}