cpan

HTTP-Response-Encoding を Release したのでお知らせします。

どういうものかというと、こういうものです。

use LWP::UserAgent;
use HTTP::Response::Encoding;

my $ua = LWP::UserAgent->new();
my $res = $ua->get("http://www.example.com/");
warn $res->encoding;
print $res->decoded_content;

見てのとおり、このモジュールはHTTP::Responseencodingdecoded_contentの両メソッドを追加します。encodingの情報は、Content-Type:ヘッダーからとっています。

意外に知られていませんが、LWP::UserAgentには、metaタグをparseしています。なのでGETした場合には、かなりの高確率でcharset=whateverを取り出す事が出来ます。本モジュールはそれを利用しているのです。

大した量ではないので、全ソースをこちらにコピペしておきます。

sub HTTP::Response::encoding {
    require Encode;
    my $self = shift;
    my $content_type = $self->headers->header('Content-Type');
    return unless $content_type;
    $content_type =~ /charset=([A-Za-z0-9_\-]+)/io;
    return unless $1;
    my $enc = Encode::find_encoding($1);
    return unless $enc;
    $self->{__encoding} = $enc;
    return $enc->name;
}

sub HTTP::Response::decoded_content {
    require Carp;
    require Encode;
    my $self = shift;
    return unless $self->content;
    unless ($self->encoding){
        Carp::croak "Cannot find encoding for ", $self->request->uri;
    }
    return $self->{__encoding}->decode($self->content);
}

Enjoy!

Dan the Perl Monger