在 Perl 中,如何将字节数组转换为 Unicode 字符串?
In Perl, how can I convert an array of bytes to a Unicode string?
有人知道怎么做吗?这可能吗?
我读过有关解码和编码的内容,但由于我不是专家,所以不知道它是否有帮助。
当然可以。如果你有字节数组
my @bytes = (0xce, 0xb1, 0xce, 0xb2, 0xce, 0xb3);
您需要先将它们组合成一串八位字节:
my $x = join '', map chr, @bytes;
然后,您可以使用 utf8::decode 将其转换为 UTF-8 就地 :
utf8::decode($x)
or die "Failed to decode UTF-8";
您也可以使用Encode::decode_utf8。
#!/usr/bin/env perl
use 5.020; # why not?!
use strict;
use warnings;
use Encode qw( decode_utf8 );
use open qw(:std :utf8);
my @bytes = (0xce, 0xb1, 0xce, 0xb2, 0xce, 0xb3);
my $x = join '', map chr, @bytes;
say "Using Encode::decode_utf8";
say decode_utf8($x);
utf8::decode($x)
or die "Failed to decode in place";
say "Using utf8::decode";
say $x;
输出:
C:\Temp> perl tt.pl
Using Encode::decode_utf8
αβγ
Using utf8::decode
αβγ
Encode
允许您在多种字符编码之间进行转换。它的功能允许您指定在 encoding/decoding operations fail 情况下会发生什么,而在 utf8::decode
情况下您只能明确检查 success/failure.
有人知道怎么做吗?这可能吗?
我读过有关解码和编码的内容,但由于我不是专家,所以不知道它是否有帮助。
当然可以。如果你有字节数组
my @bytes = (0xce, 0xb1, 0xce, 0xb2, 0xce, 0xb3);
您需要先将它们组合成一串八位字节:
my $x = join '', map chr, @bytes;
然后,您可以使用 utf8::decode 将其转换为 UTF-8 就地 :
utf8::decode($x)
or die "Failed to decode UTF-8";
您也可以使用Encode::decode_utf8。
#!/usr/bin/env perl
use 5.020; # why not?!
use strict;
use warnings;
use Encode qw( decode_utf8 );
use open qw(:std :utf8);
my @bytes = (0xce, 0xb1, 0xce, 0xb2, 0xce, 0xb3);
my $x = join '', map chr, @bytes;
say "Using Encode::decode_utf8";
say decode_utf8($x);
utf8::decode($x)
or die "Failed to decode in place";
say "Using utf8::decode";
say $x;
输出:
C:\Temp> perl tt.pl Using Encode::decode_utf8 αβγ Using utf8::decode αβγ
Encode
允许您在多种字符编码之间进行转换。它的功能允许您指定在 encoding/decoding operations fail 情况下会发生什么,而在 utf8::decode
情况下您只能明确检查 success/failure.