This makes no sense:
use utf8;
utf8_decode("My favorite pokemon is ブラッキー")

«use utf8;» will decode, and then you try to decode again?

Contrary to what you say, @valid does not contain valid UTF-8 strings, since you remove the UTF-8 encoding.


I'm trying to find a way to determine whether some arbitrary blob of data is text or just binary.

If there are any characters above 255, then it's surely text. Beyond that, it's impossible to determine.

$ perl -MDevel::Peek -e'$_="\x{00C9}ric"; Dump($_);' FLAGS = (POK,pPOK) PV = 0x826d060 "\311ric"\0 # Text (My name) $ perl -MDevel::Peek -e'$_=pack("N", 0xC9726963); Dump($_);' FLAGS = (POK,pPOK) PV = 0xa16b2d8 "\311ric"\0 # Binary

(Irrelevant output removed for brevity and clarity.)

figure out a way to detect whether data is UTF-8 or just random binary:

If there are any characters above 127, just try to decode it. If you're successful, it's surely UTF-8.

my $is_utf8 = eval { decode('UTF-8', $bytes, Encode::FB_CROAK|Encode::LEAVE_SRC); 1 };

The chances of getting a false positive are extremely slim. However, if all the characters are below 128, it's impossible to determine.

$ perl -MDevel::Peek -e'$_="ABCD"; Dump($_);' FLAGS = (POK,pPOK) PV = 0x81bb060 "ABCD"\0 # Text $ perl -MDevel::Peek -e'$_=pack("N", 0x41424344); Dump($_);' FLAGS = (POK,pPOK) PV = 0x9e0a2c8 "ABCD"\0 # Binary

In reply to Re: Can't tell if UTF-8... or just binary... by ikegami
in thread Can't tell if UTF-8... or just binary... by Kirsle

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.