how can I determine how many columns a string will occupy when printed to the console?

Viewed 10

This question is restricted to strings devoid of whitespace, human-readable. I don't care about NUL or other characters that one would not find in a piece of text set down for human consumption.

This question would be useful, for instance, for generating nicely centered lines of text.

In the perl script below, we look first at strings that take up 1 column, then 2 columns, 3 columns, etc.

As we see from running this code, neither the number of bytes, nor the length of an array created by splitting a string at \B, reliably tells us how many columns a string or a character will take up when printed. Is there a way to get this number?

#!/usr/bin/env perl 
use strict; use warnings;
use feature 'say';

while(<DATA>)
{
    say '------------------------------------------';
    print;
    $_=~s/\s//g;
    my@array=split /\B/,$_;
    say length $_,' bytes, ',scalar@array,' components';
}

__DATA__
a
é
ø
ü
α 
ά
∩
⊃
≈
≠
好
üb
üü
dog
Voß
café
Schwiizertüütsch 
0 Answers
Related