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?
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)
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |