在我的终端中,它们同样宽:
ヌー平行
parallel
æøåüäöûß
我已经设法让 Perl 给出最后 2 行的长度 8,但它报告第一行的长度为 4。有没有办法让我确定ヌ的宽度是 ø 的两倍?
您可以使用Text::CharWidth的
mbswidth
。它使用 POSIX 的 wcwidth
。
use v5.14;
use warnings;
use utf8;
use open ':std', ':encoding(UTF-8)';
use Encode qw( encode_utf8 );
use Text::CharWidth qw( mbswidth );
use Unicode::Normalize qw( NFC NFD );
my @tests = (
[ "ASCII", "parallel", 8 ],
[ "NFC", NFC("æøåüäöûß"), 8 ],
[ "NFD", NFD("æøåüäöûß"), 8 ],
[ "EastAsian", "ヌー平行", 8 ],
);
for ( @tests ) {
my ( $name, $s, $expect ) = @$_;
my $length = length( $s );
my $got = mbswidth( encode_utf8( $s ) );
printf "%-9s length=%2d expect=%d got=%d\n",
$name, $length, $expect, $got;
}
ASCII length= 8 expect=8 got=8
NFC length= 8 expect=8 got=8
NFD length=13 expect=8 got=8
EastAsian length= 4 expect=8 got=8
请注意,
mbswidth
需要使用语言环境的编码进行编码的字符串,我假设上述程序中的两个位置是 UTF-8。
如果您想知道字符串根据 Unicode 应采用的列数,请参阅 Unicode 标准附件 #11。请注意,答案可能取决于一个人是否处于东亚环境中。例如,U+03A6 希腊大写字母 PHI(“Φ”)在东亚语境中占用两列,而在其他情况下仅占用一列。