如何在Perl中将gbk编码转换为utf-8编码

时间:2011-05-24 03:11:51

标签: perl encoding

我有一个简单的问题,我不知道如何在Perl中解决。我知道如何从utf-8转换为GBK,例如,从e4b8ad转换为d6d0。但我不确定如何向后退,即给定d6d0,我怎么知道e4b8ad

请赐教!非常感谢。

3 个答案:

答案 0 :(得分:3)

当你有十六进制数字时,pack是你的朋友。以下是REPL会议。注意:

  • 要反转方向,请将十六进制数字打包成八位字节,从GB八位字节解码为字符串,将字符串编码为UTF-8八位字节,将八位字节解压缩为十六进制数字。
  • GBK 已被取代。使用GB18030(由Perl中的Encode::HanExtra提供)已经强制性已有五年了。

$ use Encode qw(decode encode); use Encode::HanExtra; use Devel::Peek qw(Dump);

$ 'e4b8ad'
e4b8ad                                  # hex digits

$ pack('H*', 'e4b8ad')
中

$ Dump(pack('H*', 'e4b8ad'))
SV = PV(0x3657680) at 0x36b7188
  REFCNT = 1
  FLAGS = (PADTMP,POK,pPOK)
  PV = 0x36c0768 "\344\270\255"\0           # octets of UTF-8 encoded data
  CUR = 3
  LEN = 8

$ decode('UTF-8', pack('H*', 'e4b8ad'))
中

$ Dump(decode('UTF-8', pack('H*', 'e4b8ad')))
SV = PV(0x326c3a0) at 0x36a50c8
  REFCNT = 1
  FLAGS = (TEMP,POK,pPOK,UTF8)
  PV = 0x3698a48 "\344\270\255"\0 [UTF8 "\x{4e2d}"]     # character string
  CUR = 3
  LEN = 8

$ encode('GB18030', decode('UTF-8', pack('H*', 'e4b8ad')))
"\xd6\xd0"

$ Dump(encode('GB18030', decode('UTF-8', pack('H*', 'e4b8ad'))))
SV = PV(0x36a2da0) at 0x36b6d98
  REFCNT = 1
  FLAGS = (TEMP,POK,pPOK)
  PV = 0x36db3e8 "\326\320"\0               # octets of GB18030 encoded data
  CUR = 2
  LEN = 8

$ unpack('H*', encode('GB18030', decode('UTF-8', pack('H*', 'e4b8ad'))))
d6d0                            # hex digits

答案 1 :(得分:1)

问题的答案是:

use Encode qw( from_to );
my $gbk = "\xD6\xD0";
from_to(my $utf8 = $gbk, 'GB18030', 'UTF-8');  # E4 B8 AD

use Encode qw( decode encode );
my $gbk = "\xD6\xD0";
my $utf8 = encode('UTF-8', decode('GB18030', $gbk));  # E4 B8 AD

但是,更正常的流程如下所示:

open(my $fh_in,  '<:encoding(GB18030)', ...) or die ...;
open(my $fh_out, '>:encoding(UTF-8)',   ...) or die ...;

while (<$fh_in>) {
   ...
   print $fh_out ...;
   ...
}

必须为Encode安装Encode :: HanExtra才能找到编码。

答案 2 :(得分:0)

use Encode qw/encode decode/;
$utf8 = decode("euc-cn", $euc_cn); # ditto

您通常也可以在打开或关闭FD时指定编码,并执行必要的转换。

像魅力一样:

perl -e 'open(X,">","/tmp/x"); print X chr(0xd6).chr(0xd0);close(X)'
perl -mEncode -e 'open(X,"<","/tmp/x"); $x=<X>; print Encode::decode("euc-cn",$x);' > /tmp/xx