http://qs1969.pair.com?node_id=713297

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

When printing an UTF8 string with printf("%s"), it can actually be wider than expected due to, by example, the chinese characters that are "2 printed chars" wide on my terminal. My problem occurs when mixing letters with chinese character in a string: I'm unable to guess the actual length of the string to be printed.

The following code gives us informations about how the string is encoded inside Perl:

$ perl -MDevel::Peek -e 'use utf8; my $s="\x{5fcd}\x{65e0}\x{53ef}\x{5 +fcd}"; Dump($s); print length($s), "\n";' SV = PV(0x8154b00) at 0x8154720 REFCNT = 1 FLAGS = (PADBUSY,PADMY,POK,pPOK,UTF8) PV = 0x816ff80 "\345\277\215\346\227\240\345\217\257\345\277\215"\0 +[UTF8 "\x{5fcd}\x{65e0}\x{53ef}\x{5fcd}"] CUR = 12 LEN = 16 4

Since I know my characters are 2 characters wide, I can try to guess the "real width" is 8 using the length() function (4 * 2 = 8).

But it doesn't work anymore when I enclose my string in brackets:

$ perl -MDevel::Peek -e 'use utf8; my $s="(\x{5fcd}\x{65e0}\x{53ef}\x{ +5fcd})"; Dump($s); print length($s), "\n";' SV = PV(0x8154b00) at 0x8154720 REFCNT = 1 FLAGS = (PADBUSY,PADMY,POK,pPOK,UTF8) PV = 0x816ff80 "(\345\277\215\346\227\240\345\217\257\345\277\215)"\ +0 [UTF8 "(\x{5fcd}\x{65e0}\x{53ef}\x{5fcd})"] CUR = 14 LEN = 16 6
Now I have 6 characters, but I can't guess the "real length" is 10 (6 * 2 != 10), and the bytes length won't help...

Does anyone have an idea to measure these strings?