【问题标题】:"Cannot decode string with wide characters" appears on a weird place“无法解码带有宽字符的字符串”出现在一个奇怪的地方
【发布时间】:2010-11-09 21:57:11
【问题描述】:

我正在尝试在 UTF8 编码文本上使用 XML::RAI perl 模块,但仍然有我不太明白的错误...这是代码(它不应该做任何有用的事情):

use HTTP::Request;
use LWP::UserAgent;
use XML::RAI;
use Encode;

my $ua = LWP::UserAgent->new;


sub readFromWeb{
    my $address = shift;
    my $request = HTTP::Request->new( GET => $address );
    my $response = $ua->request( $request );
    return unless $response->code == 200;

    return decode("utf8", $response->content());
}

sub readFromRSS{
    my $address=shift;
    my $content = readFromWeb $address;
    my $rai = XML::RAI->parse_string($content);
          #this line "causes" the error
}


readFromRSS("http://aktualne.centrum.cz/export/rss-hp.phtml");
     #I am testing it on this particular RSS

错误是:

 Cannot decode string with wide characters at /usr/lib/perl5/5.8.8/i686-linux/Encode.pm line 166.

我不知道这是我的错还是 XML::RAI 的错。如果 $content 已经从 utf8 解码,我看不出这些宽字符在哪里......

编辑:由于某种原因我仍然不明白,删除“解码”部分实际上解决了问题。

【问题讨论】:

    标签: perl unicode


    【解决方案1】:

    问题在于双重解码。 XML::RAI::parse_string() 显然 需要一个 UTF-8 编码的文档并自己进行解码。如果你 传入一个已经解码的字符串,第二次解码会失败, 当然:

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    use Encode qw( decode );
    use LWP::Simple qw( get );
    
    my $xml = get("http://aktualne.centrum.cz/export/rss-hp.phtml");
    
    $xml = decode('UTF-8', $xml);
    $xml = decode('UTF-8', $xml); # dies: Cannot decode string with wide characters ...
    

    所以只需跳过decode() 步骤就可以了。

    【讨论】:

      猜你喜欢
      • 2012-10-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-20
      • 2012-08-15
      • 2011-01-16
      相关资源
      最近更新 更多