Is the original data in utf8? If the data source is utf8, and you read it in as "raw bytes", the number of unicode characters will be the sum of bytes in the ascii range (x00-x7F) plus bytes greater than 0xC2 0xC0. In other words:
open( INPUT, "<:raw", "some_file.utf8" ) or die "bleah: $!"; { local $/; $_ = <INPUT>; } my $nbytes = length(); my $nchars = tr/\x00-\x7F\xC2-\xFF//;
The reason why that is true is that in utf8, every ascii character is just a single-byte ascii character, but every "wide character" (above ascii) is a sequence of two or more bytes, in which the first byte must have at least two of its highest bits set, and each successive byte comprising the one single character must have just the 8th bit set (the 7th bit must be zero) -- i.e. non-initial bytes in wide characters must always be less than 0xC0 fall between 0x80 and 0xBF, inclusive. Only one byte per character (the first one) can (and must) be greater than 0xC0.

While it is conceivable to have "wide characters" whose first byte is 0xC0 or 0xC1, this would actually constitute "malformed utf8", in the sense that two bytes are being used to express code points within the ascii range, which would be a dirty trick to play on anybody.

Check the "Unicode Encodings" section of perlunicode to see a more detailed explanation of utf8.

(updated to improve clarity and accuracy)


In reply to Re: Another use bytes and length issue by graff
in thread Another use bytes and length issue by zubster

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.