スクリプトと入力ファイルが同じエンコードでエンコードされている場合、コードはそのまま動作します。
$ cat>test.html
ùmbrella ùnder ùùùùù ùtters
$ perl a.pl
$ cat out/test.html
umbrella under uuuuu utters
あなたのプログラムは、しかし、バグがあります。私たちがUTF-8について話しているとしましょう。あなたが持っていた場合、これはありませんので、悪いですが、Perlは実際に
$str =~ s/\xC3\xB9/u/g;
見て、想像
$str =~ s/[ùú]/u/g;
Perlは
$str =~ s/[\xC3\xB9\xC3\xBA]/u/g;
これは
ù
(
C3 B9
)
uu
に変わるだろうと見るであろう
é
(
C3 A9
)を
u<garbage>
とする。
プログラムで非ASCII文字を認識するためには、プログラムファイルがUTF-8でエンコードされていることを確認し、ファイルの先頭にuse utf8;
を追加する必要があります。 use utf8;
では、Perlは
$str =~ s/[ùú]/u/g;
かという
$str =~ s/[\xF9\xFA]/u/g; # F9 and FA are the Unicode Code Points for ù and ú
を見ただし、use utf8;
を追加するソリューションの半分だけです。 Perlが正規表現をどのように見えるかを変更しましたが、$str
を変更していないため、これ以上一致する可能性はありません。私たちは常にあなたの入力をデコードù
(F9
)
のUnicodeのコードポイントでù
(C3 B9
)のエンコーディングを比較しています。常にあなたの出力をエンコードする。
すでに1つの入力(プログラム自体)をデコードしました。今度はファイルの内容と同じことをする必要があります。
同様に、出力をエンコードする必要があります。これには、ファイルの内容だけでなく、警告がSTDERRに出力されます。
ことの多くは、
use open ':std', ':encoding(UTF-8)';
によって行われるそれはSTDIN、STDOUTとSTDERRへのエンコード層を追加し、プラグマの字句範囲内で開かれたファイルのデフォルトのエンコーディング層を設定します。
#!/usr/bin/perl
use utf8;
use open ':std', ':encoding(UTF-8)';
use strict;
use warnings;
my $in_qfn = 'test.html';
my $out_qfn = 'out/test.html';
# :encoding(UTF-8) is added by "use open".
open(my $in_fh, '<', $in_qfn) or die("Can't open \"$in_qfn\": $!\n");
open(my $out_fh, '>', $out_qfn) or die("Can't create \"$out_qfn\": $!\n");
while (<$in_fh>) {
s/[ùú]/u/g;
print($out_fh $_);
}
[ファイル::読まを使用する場合は、そのopen
がuse open
の範囲ではないため、ファイルをデコード(またはそれを自分でデコード)するためにそれを伝える必要があります。
#!/usr/bin/perl
use utf8;
use open ':std', ':encoding(UTF-8)';
use strict;
use warnings;
use File::Slurp qw(read_file write_file);
my $in_qfn = 'test.html';
my $out_qfn = 'out/test.html';
my $file = read_file($in_qfn, binmode => ':encoding(UTF-8)');
$file =~ s/[ùú]/u/g;
write_file($out_qfn, { binmode => ':encoding(UTF-8)' }, $file);
@ iiamありがとうございました!私は "use utf8;"を追加しなければならなかった。上にも同様に – Xavia
@サイアム:あなたはPythonを考えている!それはPerlの単なるコメントです。 – Borodin
[File :: Slurpが壊れていて間違っています。](http://blogs.perl.org/users/leon_timmermans/2015/08/fileslurp-is-broken-and-wrong.html) – ThisSuitIsBlackNot