Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: How to test if a string is unicode string?

by ikegami (Patriarch)
on Apr 04, 2025 at 15:36 UTC ( [id://11164579]=note: print w/replies, xml ) Need Help??


in reply to How to test if a string is unicode string?

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?

  • Decoded text?
  • UTF-8?
  • UTF-16?
  • A string stored using the upgraded storage format?

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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11164579]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2026-02-18 06:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.