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?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.