You might want to look at your OS C library, and see what it provides - it may have a function you can call with XS or Inline::C.

The following code ought to work on my (Linux) system, except that it's thinking the characters given in the example aren't printable - and are hence given a length of -1. My manual says "The behaviour of wcwidth depends on the LC_CTYPE category of the current locale", but gives no hint on what to set it to.

$ cat ./uu #!/usr/bin/perl use 5.010; use strict; use warnings; use Inline 'C'; my $s0 = "Hello, world"; my $s1 = "\x{5fcd}\x{65e0}\x{53ef}\x{5fcd}"; my $s2 = "($s1)"; my $l0 = w_length ($s0); my $l1 = w_length ($s1); my $l2 = w_length ($s2); say "$l0: $s0"; say "$l1: $s1"; say "$l2: $s2"; __END__ __C__ #include <wchar.h> int w_length(char* str) { int i; int length; char c; i = 0; length = 0; while(c = str[i++]) { int l; l = wcwidth(c); length += l > 0 ? l : 0; } return length; } $ LC_CTYPE=en_US.UTF-8 perl -CO ./uu 12: Hello, world
0: 忍无可忍
2: (忍无可忍)

So, there's something missing in my solution, but I'm far from a Unicode expert, let alone the provided library on my system, but it maybe something you can use as a start.


In reply to Re: The “real length" of UTF8 strings by JavaFan
in thread The “real length" of UTF8 strings by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.