Perl 日本語処理 もう文字化けなんて見たくない

  • script は UTF-8 で書く
  • use utf8; を使用し,perl に script が UTF-8 で書かれているという事を教える
use strict;
use warnings;
use utf8;
open my $in,  '<:encoding(euc-jp)', $infile  or die "$!";
open my $out, '>:encoding(utf8)',   $outfile or die "$!";
  • 外部から取り込むテキストデータは適切にデコードする
use Encode;

my $response = $ua->get($url)
my $data = decode('shiftjis', $response->content);
  • 外部に出力するテキストデータは適切にエンコードする
use Encode;

print encode('utf8', $data)
binmode STDERR, ":raw :encoding(eucjp)";

おまけ

・ utf8 プラグマは lexical scope
・ no utf8; で,utf8 を無効にできる
・ Unicode(UTF8)フラグは perl 内部のものなので,このフラグが立ったテキストデータを出力してはいけない

蛇足

perl -MEncode -le 'print for Encode->encodings(":all");'


参考