All those are equivalent.

The fastest way of writing it is probably

$STRING =~ tr/\x00-\xFF//c # Can be used as a boolean.

But do they do what you asked?


Does it check if it's plain ASCII?

No. ASCII only has 128 characters, so the following would be closer:

sub isASCII { !!( $_[0] =~ tr/\x00-\x7F//c ) }

(!! just normalizes the result to be the true (&PL_sv_yes) or the false (&PL_sv_no).)

But does it work?

Not quite. It will always return true when provided ASCII, but it won't necessarily return false is provided non-ASCII.

my $ascii = encode( "ASCII", "\N{LATIN SMALL LETTER A}" ); isASCII( $ascii ) # true (OK. true positive) my $decoded_text = "\N{U+2660}"; isASCII( $decoded_text ) # false (OK. true negative) my $temperature = 18; my $data_packet = pack( 's>', $temperature ); isASCII( $data_packet ) # true (Error. false positive)

Does it check if it's plain Unicode?

What does "Unicode" mean?

Whichever one you want to do, it will run unto the same problem as checking if a string is ASCII: You can't eliminate false positives. (Well except checking the storage format. That can be done reliably, but relying on the result is a bug.)


You can't tell if a string is ASCII or "Unicode" (whichever definition) reliably. If your code needs to deal with strings in multiple formats and distinguish between them, it will need to be told of the format of the strings.


In reply to Re: How to test if a string is unicode string? by ikegami
in thread How to test if a string is unicode string? by harangzsolt33

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.