Perl 日本語処理 もう文字化けなんて見たくない
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");'
参考