Perl substr基于字节

Min*_* Le 3 perl utf-8 amazon-simpledb

我正在为我的应用程序使用SimpleDB.除非一个属性的限制是1024字节,否则一切顺利.因此,对于一个长字符串,我必须将字符串切成块并保存.

我的问题是,有时我的字符串包含unicode字符(中文,日文,希腊文),该substr()函数基于字符数而不是字节.

我试图使用use bytes字节语义或更晚, substr(encode_utf8($str), $start, $length)但它根本没用.

任何帮助,将不胜感激.

ike*_*ami 5

设计UTF-8使得字符边界易于检测.要将字符串拆分为有效UTF-8的块,您只需使用以下内容:

my $utf8 = encode_utf8($text);
my @utf8_chunks = $utf8 =~ /\G(.{1,1024})(?![\x80-\xBF])/sg;
Run Code Online (Sandbox Code Playgroud)

然后

# The saving code expects bytes.
store($_) for @utf8_chunks;
Run Code Online (Sandbox Code Playgroud)

要么

# The saving code expects decoded text.
store(decode_utf8($_)) for @utf8_chunks;
Run Code Online (Sandbox Code Playgroud)

示范:

$ perl -e'
    use Encode qw( encode_utf8 );

    # This character encodes to three bytes using UTF-8.
    my $text = "\N{U+2660}" x 342;

    my $utf8 = encode_utf8($text);
    my @utf8_chunks = $utf8 =~ /\G(.{1,1024})(?![\x80-\xBF])/sg;

    CORE::say(length($_)) for @utf8_chunks;
'
1023
3
Run Code Online (Sandbox Code Playgroud)