gpt4 book ai didi

xml - Perl utf8 binmode 意外结果

转载 作者:数据小太阳 更新时间:2023-10-29 03:00:23 24 4
gpt4 key购买 nike

为什么 binmode as raw 会产生元音变音?能否详细说明“Zurich”字符串在 Perl 中的内部存储方式?只是有点迷路。

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&#252;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。后者是不正确的,即使在这个例子中两者看起来是等价的。

关于xml - Perl utf8 binmode 意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46063174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com