I think you can use pack and unpack to accomplish this:

my $utf8; { local $^W; # warnings are thrown when unpacking # invalid UTF8, ignore them, we'll check # for problems be seeing if the string is # null at the end and shouldn't be. $utf8 = pack "U*", unpack "U*", $raw; } deal_with_malformed_utf8() if length $utf8 == 0 and length $raw != 0;

If you are using a very recent version (i.e. experimental) of perl you can use the Encode module's decode_utf8 function, or use the internal function utf8::decode which it is implemented with:

use Encode; my $string = decode_utf8($bytes); deal_with_malformed_utf8() unless defined $string # or utf8::decode($string = $bytes) # of course, you can just or deal_with_malformed_utf8();# use one variable, and not # keep the raw bytes.

(update: (Because it may seem odd:) The rational behind the decode in the function names is that these functions "[decode] from UTF-8 to a sequence of logical characters." )</o>

Also in the experimental version of perl the Encode module provides a _utf8_on function that will turn on that flag which says "this value carries UTF-8", however the documentation advises that this function is internal and may change, and that one must be very sure you are dealing with valid UTF-8 first.


In reply to Re: How do you impose by wog
in thread How do you impose &quot;character&quot; orientation on a string? by John M. Dlugosz

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.