Skip to content

Show Time/Date/Weather in Perl

This little console program scrapes from http://www.timeanddate.com/ and prints to the screen. A handy little program I often use to tell the time in other cities.

sub getCityTime {  
  use LWP::Simple;
  my %hash;

  #new york http://www.timeanddate.com/worldclock/city.html?n=179
  #darwin   http://www.timeanddate.com/worldclock/city.html?n=72
  #tokyo    http://www.timeanddate.com/worldclock/city.html?n=248
  #peru     http://www.timeanddate.com/worldclock/city.html?n=131
  #         http://www.timeanddate.com/worldclock/results.html?query=darwin

  
  $url = "http://www.timeanddate.com/worldclock/city.html?n=";
  
  %hash = ( 'newyork', '179', 
            'darwin',   '72', 
            'tokyo',    '248', 
            'lima',     '131'
          );
  
  my $html = get($url.$hash{$_[0]})
    or die "Couldn't connect to the timeanddate.com website.";
    
  $html =~ m!<span>([\s\w,;']*)</span>!;
  print "Location ======&gt; ".$1."\n";  

  $html =~ m!<strong>([\s\w:,]*)</strong>!;
  print "Date/Time =====&gt; ".$1."\n";  

  $html =~ m!<strong>(\d{1,3})[\s\w:,;&amp;]*</strong>!;
  print "Temperature ===&gt; ".$1.chr(167)."F\n";  

}

# MAIN

if ($ARGV[0] ne "") {
  getCityTime( $ARGV[0] );
}
else {

  print "\nDisplays the time from TimeAndDate.com, based on city.\n\n";
  
  getCityTime( "newyork" );
  print "==============================\n";
  getCityTime( "lima" );
  print "==============================\n";
  getCityTime( "tokyo" );
  print "==============================\n";
  getCityTime( "darwin" );  

}

Categories

Perl

Dan View All

Blog owner.

%d bloggers like this: