shift-jis在perl中的解码/编码

shift-jis在perl中的解码/编码,perl,encoding,decode,encode,shift-jis,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

当我尝试解码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"; 使用编码qw(解码编码); $val=; 打印“\n解码前:$val”; my$ustr=Encode::decode(“shiftjis”,$val); 打印“\n解码后:$ustr”; 打印“\n编码前:$ustr”; $val=Encode::Encode(“shiftjis”,$ustr); 打印“\n编码后:$val”; 当我使用字符串时:helloソ世界在输入它得到正确的解码和编码回来,即解码前和编码后打印在上述代码打印相同的值。 但当我尝试另一个字符串时,如:ⅢⅡⅢⅣⅤⅦⅧⅨⅩ

最终输出被弄乱了

这是一个特定于perl库的问题,还是一个一般的shift jis映射问题?
有什么解决方法吗?

您缺少错误检查

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 …

您只需将
shiftjis
替换为
cp932


是-这是一个臭名昭著的问题,Microsoft Windows中使用的编码不是真正的“shift JIS”,而是CP932。谢谢,它在Windows上运行得非常好。但是它在unix平台上不起作用,我们需要为Linux、AIX等平台使用任何特定的编码吗?@Sush-Hmm,我不知道为什么它对您不起作用。。。有日文编码的映射表(比如,),所以它应该独立于平台工作——事实上,我确保它在Linux上正常工作。我怀疑你的问题在其他地方。就目前而言,你的答案是正确的,但实际问题比这稍微深一点。