在perl中移位jis解码/编码

时间:2011-04-02 07:00:18

标签: perl encoding decode encode shift-jis

当我尝试解码shift-jis编码的字符串并对其进行编码时,某些字符会出现乱码: 我有以下代码:

use Encode qw(decode encode);
$val=;
print "\nbefore decoding: $val";
my $ustr = Encode::decode("shiftjis",$val);
print "\nafter decoding: $ustr";
print "\nbefore encoding: $ustr";
$val = Encode::encode("shiftjis",$ustr);
print "\nafter encoding: $val";

当我使用字符串:helloソworld in input时,它会被正确解码并编码回来,即。在解码之前和编码后打印在上面的代码中打印相同的值。 但是当我尝试另一个字符串时:ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ

结束输出乱码。

它是perl库特定的问题还是一般的移位jis映射问题? 它有什么解决方案吗?

2 个答案:

答案 0 :(得分:2)

您缺少错误检查。

use utf8;
use Devel::Peek qw(Dump);
use Encode qw(encode);

sub as_shiftjis {
    my ($string) = @_;
    return encode(
        'Shift_JIS',    # http://www.iana.org/assignments/character-sets
        $string,
        Encode::FB_CROAK
    );
}

Dump as_shiftjis 'helloソworld';
Dump as_shiftjis 'ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ';

输出:

SV = PV(0x9148a0) at 0x9dd490
  REFCNT = 1
  FLAGS = (TEMP,POK,pPOK)
  PV = 0x930e80 "hello\203\\world"\0
  CUR = 12
  LEN = 16
"\x{2160}" does not map to shiftjis at …

答案 1 :(得分:2)

您只需将shiftjis替换为cp932

http://en.wikipedia.org/wiki/Code_page_932