Skip to content

Instantly share code, notes, and snippets.

@bayashi
Created March 26, 2011 08:02
Show Gist options
  • Save bayashi/888120 to your computer and use it in GitHub Desktop.
Save bayashi/888120 to your computer and use it in GitHub Desktop.
TokyoDenryoku.pl
#!/usr/bin/perl
use strict;
use warnings;
use LWP::UserAgent;
use URI::Fetch;
use Cache::FileCache;
use Data::Dumper;
my $TSV_URL = 'http://www.tepco.co.jp/forecast/html/images/juyo-j.csv2';
my $CACHE = Cache::FileCache->new({
namespace => 'ToKyoDenryoku',
cache_root => '/tmp',
default_expires_in => 60,
cache_depth => 1,
});
my $UA = LWP::UserAgent->new(
timeout => 10,
agent => 'bayashi_proxy/1.0',
);
main();
sub main {
my $response = get_csv();
if ($response =~ m!^disconnected\. !) {
die "$response";
}
elsif ($response->is_error) {
die 'could not get tsv:'. $response->http_status;
}
my $result = parse_content($response->content);
print Dumper($result)."\n";
}
sub parse_content {
my $content = shift || '';
my @lines = split /\n/, $content;
my $result;
# CSVの更新日時
$result->{update} = shift @lines;
$result->{update} =~ s/ UPDATE$//;
shift @lines; # 2行目は見出し
# peak
my @peak = split(/\,/, shift @lines);
for my $key (qw/electricity hour update_date update_time/) {
$result->{peak}{$key} = shift @peak;
}
shift @lines; # 空行
shift @lines; # 見出し
for my $line (@lines) {
my ($date, $time, $electricity, $y_electricity) = split /\,/, $line;
$result->{$date}{$time} = +{
now => $electricity,
yesterday => $y_electricity,
};
}
return $result;
}
sub get_csv {
my $response = URI::Fetch->fetch(
$TSV_URL,
Cache => $CACHE,
UserAgent => $UA,
NoNetwork => 30,
)
or return 'disconnected. ' . URI::Fetch->errstr;
return $response; # URI::Fetch::Response obj
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment