Are you getting actual utf8 data from a file handle that does not use the ":utf8" PerlIO layer (so that perl begins by assuming it's just a raw byte stream)? And if that's the case, are you trying to work out a way to use "byte-semantics" regexen where possible, and "character-semantics" only when necessary?
If that's your situation, here's an easy, low-cpu-load method to check whether a raw byte string needs be tagged as utf8:
(updated as per fenLisesi's reply -- thanks!)if ( length($string) > $string =~ tr/\x00-\x7f// ) { $string = decode( 'utf8', $string ); }
Or, given that the original string is not tagged as a perl-internal utf8 scalar value (utf8 flag is off), this might be just as good or better:
I'm not actually sure whether one way is faster than the other, or whether the relative speed would depend on your data; "length()" and "tr///" are both pretty fast whereas a regex match is slower, but tr always processes the whole string, whereas that regex match will stop at the first non-ascii byte.if ( $string =~ /[\x80-\xff]/ ) { $string = decode( 'utf8', $string ); }
In reply to Re^3: Behaviour of Encode::decode_utf8 on ASCII
by graff
in thread Behaviour of Encode::decode_utf8 on ASCII
by jbert
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |