转换字符串中的字符

gam*_*ver 3 string perl

我有一个字符串:

Why RUNAS Windows \xee\x80\x80\x45xplorer\xee\x80\x81 Doesn\xe2\x80\x99t 
Work After Installing IE7 St\xc3\xa5le
Run Code Online (Sandbox Code Playgroud)

我通过阅读XML文件得到的.这是一个UTF-8字符串.现在我想打印其等效的unicode字符,以便我得到:

Why RUNAS Windows ?Explorer? Doesn’t Work After Installing IE7 Ståle 
Run Code Online (Sandbox Code Playgroud)

我尝试了一个小程序:

use strict;
use utf8;
use Encode;

my $str = "Why RUNAS Windows \xee\x80\x80\x45xplorer\xee\x80\x81 Doesn\xe2\x80\x99t Work After Installing IE7 St\xc3\xa5le";
print $str;
Run Code Online (Sandbox Code Playgroud)

它工作了!!

问题是当我尝试从文件中读取字符串时,它不会转换.所以以下内容不会产生unicode输出:

use strict;
use utf8;
use Encode;
my $str = <DATA>;
$str = decode("utf8", $str);
open OUT, ">", "o.txt" or die;
binmode(OUT,":utf8");
print OUT $str;
__DATA__
Why RUNAS Windows \xee\x80\x80\x45xplorer\xee\x80\x81 Doesn\xe2\x80\x99t Work After Installing IE7 St\xc3\xa5le
Run Code Online (Sandbox Code Playgroud)

Rob*_*t P 5

两个示例之间的区别在于,第一个示例中的反斜杠在编译时被插入为字节,而在第二个示例中,它们是文字文本.您正在读取第二个示例中的字符序列"\","x","e","e",但第一个将其转换为内存中的单个unicode字符.

如果XML文件包含unicode字符,Perl可以很好地读取它们; 它们不需要如图所示进行转义.

如果必须将这些unicode字符保留为字符序列,请考虑使用CPAN中的库对其进行解码.一目了然,Encode :: Escape看起来会满足您的需求:

#!/usr/bin/perl
use strict;
use warnings;
use Encode::Escape;

while (<DATA>) {
    chomp;
    print decode 'unicode-escape', $_; # convert byte references to (utf-8) bytes
}

__DATA__
Why RUNAS Windows \xee\x80\x80\x45xplorer\xee\x80\x81 Doesn\xe2\x80\x99t
Work After Installing IE7 St\xc3\xa5le
Run Code Online (Sandbox Code Playgroud)

可能还有其他人.