计算等宽字体字符串的宽度

Compute the width of a string in monspaced font

为了在终端中正确格式化一些文本(我假设使用等宽字体),我需要计算字符串的“长度”。棘手的部分是我需要它在显示时使用的长度(固定宽度字符的数量)。

我最初使用的是 length 函数,但它 returns 代码点的数量 。我还尝试使用以下方法计算 graphemes 的数量:

sub width {
    my $str = shift;
    my $count = 0;
    while ($str =~ /\X/g) {
        $count++;
    }
    return $count;
}

(感谢 Tom Christiansen)。

但这仍然不是我所需要的,因为一些字素与我的字体(SF Mono Regular)是双倍宽度的,例如表情符号和亚洲字符。

经过进一步研究,我找到了 Text::CharWidth CPAN 模块,它提供了 mbswidth 功能,正是我需要的。

use Text::CharWidth qw(mbswidth);

mbswidth (""); # returns 4
mbswidth ("あら"); # returns 4