WWW::Mechanize と文字コード

WWW::Mechanize は、

  1. HTTP レスポンスヘッダ部分の Content-type で設定されている charset
  2. HTTP レスポンスのボディに記述されている文字コード
    meta 要素で設定されている Content-Type の charset

を参照して、データの文字列を Perl 内部の文字列にデコードをしている。

レスポンスを受信する時も、リクエストを送信する時も文字コードには注意

例えば、

use Encode;
use WWW::Mechanize;
use utf8;

my $mech = News::Mechanize->new;
$mech->get('http://www.example.com/');
$mech->follow_link(url_regex => qr|/post|i);
$mech->submit_form(
    form_number => 1,
    fields => {
        id         => $id,
        url        => $url,
        # Perl 内部文字列ではない場合、この時点で
        # Perl の内部文字列にデコードする
        # この場合は、UTF-8 から内部文字列にデコードしている
        publisher  => decode_utf8($publihser),
        title      => decode_utf8($title),
        article    => decode_utf8($article),
        categoryId => $category,
        timestamp  => $timestamp,
    },
);

unless ($mech->success) {
	print encode('utf-8', $mech->content);
} else {
    ...
}