Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: The “real length" of UTF8 strings

by massa (Hermit)
on Sep 24, 2008 at 00:16 UTC ( #713326=note: print w/ replies, xml ) Need Help??


in reply to The “real length" of UTF8 strings

For any UTF8 string, we have four "lengths":

  1. the length in codepoints:
    perl -C63 -MDevel::Peek -Mutf8 -le '$_="(\x{5fcd} Guimarăes)"; Dump($_ +); print length($_); print' SV = PV(0x8154b00) at 0x8153bd4 REFCNT = 1 FLAGS = (POK,pPOK,UTF8) PV = 0x8170460 "(\345\277\215 Guimar\303\243es)"\0 [UTF8 "(\x{5fcd} +Guimar\x{e3}es)"] CUR = 16 LEN = 20 13
    (忍 Guimarăes)
  2. the length in graphemes (the "a" is one, the composing "~" is another):
    perl -C63 -MDevel::Peek -Mutf8 -MUnicode::Normalize -le '$_="(\x{5fcd} + Guimarăes)"; $_ = NFD $_; Dump($_); print length($_); print' SV = PV(0x8154b00) at 0x8153bd4 REFCNT = 1 FLAGS = (POK,pPOK,UTF8) PV = 0x816feb8 "(\345\277\215 Guimara\314\203es)"\0 [UTF8 "(\x{5fcd} + Guimara\x{303}es)"] CUR = 17 LEN = 20 14
    (忍 Guimarães)
  3. the length in columns of text used (the string has one wide character):
    perl -C63 -MDevel::Peek -Mutf8 -mText::CharWidth=mbswidth -le '$_="(\x +{5fcd} Guimarăes)"; Dump($_); print mbswidth($_); print' SV = PV(0x8154b00) at 0x8153bd4 REFCNT = 1 FLAGS = (POK,pPOK,UTF8) PV = 0x8170460 "(\345\277\215 Guimar\303\243es)"\0 [UTF8 "(\x{5fcd} +Guimar\x{e3}es)"] CUR = 16 LEN = 20 14
    (忍 Guimarăes)
  4. the length in bytes of the string (notice I didn't print the string after the encode):
    perl -C63 -MDevel::Peek -Mutf8 -mEncode=encode_utf8 -le '$_="(\x{5fcd} + Guimarăes)"; Dump($_); print length(encode_utf8 $_)' SV = PV(0x8154b00) at 0x8153bd4 REFCNT = 1 FLAGS = (POK,pPOK,UTF8) PV = 0x8170460 "(\345\277\215 Guimar\303\243es)"\0 [UTF8 "(\x{5fcd} +Guimar\x{e3}es)"] CUR = 16 LEN = 20 16
[]s, HTH, Massa (κς,πμ,πλ)


Comment on Re: The “real length" of UTF8 strings
Select or Download Code
Re^2: The “real length" of UTF8 strings
by Anonymous Monk on Sep 24, 2008 at 05:01 UTC

    Thank you all for your help solving this problem. The Text::CharWidth module is definitely what I need and probably the quickest solution to implement.

    Thx ^_^*

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://713326]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (12)
As of 2015-07-06 16:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (77 votes), past polls