Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
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

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

  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (2)
As of 2021-12-01 02:55 GMT
Find Nodes?
    Voting Booth?

    No recent polls found