2007年04月17日 22:30 [Edit]
CPAN - HTTP::Response::Encoding Released!
どういうものかというと、こういうものです。
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::Responseにencodingとdecoded_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
Posted by dankogai at 22:30│Comments(1)│TrackBack(2)
この記事へのトラックバックURL
この記事へのソーシャルブックマーク
この記事へのトラックバック
というわけで先ほど0.03を上げました。
404 Blog Not Found:CPAN - HTTP::Response::Encoding Released!これテスト通りません.
CPAN - MANIFESTと._file【404 Blog Not Found】at 2007年04月18日 14:50
Encode-2.21のReleaseに呼応して、HTTP-Response-Encoding を Update したのでお知らせします。
.cpan { list-style-image: url(http://search.cpan.org/favicon.ico) }
on CPAN (coming soon)
http://www.dan.co.jp/~dankogai/cpan/HTTP-Response-Encoding-0...
CPAN - HTTP::Response::Encoding Updated to 0.05!【404 Blog Not Found】at 2007年05月12日 18:42
この記事へのコメント
これテスト通りません.
t/01-file.t の最後でt/t-null.htmlを読もうとしていますが,このファイルがディストリビューションにないからです.それと,._t-euc-jp.html, ._t-iso-2022-jp.html, e.t.c ってファイルがあります.消し忘れではないかと
t/01-file.t の最後でt/t-null.htmlを読もうとしていますが,このファイルがディストリビューションにないからです.それと,._t-euc-jp.html, ._t-iso-2022-jp.html, e.t.c ってファイルがあります.消し忘れではないかと
Posted by k.daiba at 2007年04月18日 13:30

