为什么binmode原始会产生变音符号?是否可以详细说明Perl内部如何存储“ Zurich”字符串?只是有点迷路了。
use strict;
use warnings;
my $filename = "result-test-encoding-raw.xml";
open(my $fh,'>', $filename) or die "die";
#binmode $fh, ':utf8'; #bad umlaut
binmode $fh, ':raw'; #good umlaut
print $fh '<?xml version="1.0" encoding="UTF-8"?>';
print $fh '<node>';
my $line_text = 'Zürich';
print $fh $line_text;
print $fh ' next ';
$line_text = 'Zürich';
print $fh $line_text;
print $fh '</node>';
close($fh);
您丢失了use utf8;
,它告诉Perl您的源代码是使用UTF-8编码的。
默认情况下,源文件应使用US-ASCII编码。
如果您使用UTF-8对源文件进行了编码,但未将其告诉Perl(通过使用use utf8;
),则Perl会将其视为使用US-ASCII进行编码。对于字符串文字,Perl只会将字节映射到字符串字符(而不是拒绝非ASCII字符)。这意味着$line_text
包含5A.C3.BC.72.69.63.68
。
当您将这些字符传递到带有编码层的文件句柄时,编码层会将这些字符视为Unicode代码点(Zürich
),并产生适当的字节来表示这些字符。
如果您使用UTF-8对源文件进行了编码,并且告诉了Perl(通过使用use utf8;
),则Perl会将其视为使用UTF-8进行编码(相应地对其进行解码)。这意味着$line_text
包含5A.FC.72.69.63.68
。
当您将这些字符传递到带有编码层的文件句柄时,编码层会将这些字符视为Unicode代码点(Zürich
),并产生适当的字节来表示这些字符。
use strict;
use warnings;
use utf8; # Source code is encoded using UTF-8.
use open ':std', ':encoding(UTF-8)'; # Terminal expects UTF-8. Default encoding for files.
my $filename = "result-test-encoding-raw.xml";
open(my $fh, '>', $filename)
or die("Can't create \"$filename\": $!\n");
...
print $fh 'Zürich';
...
请注意,我使用:encoding(UTF-8)
代替:utf8
。后者是不正确的,即使在此示例中两者看起来相同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句