这是否正常?一些错误消息已经解码,一些需要解码才能获得正确的输出.
#!/usr/bin/env perl
use warnings;
use strict;
use utf8;
use open qw(:utf8 :std);
use Encode qw(decode_utf8);
# ...
if ( not eval{
# some error-messages (utf8) are decoded some are not
1 }
) {
if ( utf8::is_utf8 $@ ) {
print $@;
}
else {
print decode_utf8( $@ );
}
}
Run Code Online (Sandbox Code Playgroud)
我正确使用utf8 :: is_utf8吗?
不.任何使用utf8::is_utf8都是不正确的,因为你永远不应该使用它!使用utf8::is_utf8一个字符串的语义猜测是什么作为的实例中的Unicode错误.调试Perl或XS模块时检查变量的内部状态除外,utf8::is_utf8没有用.
它不表示变量中的值是否使用UTF-8编码.事实上,这是不可能可靠的.例如,是否"\xC3\xA9"产生了使用UTF-8编码的字符串?好吧,没有办法知道!这取决于我的意思"é","é"还是完全不同的东西.
如果变量可能包含编码和解码的字符串,则由您决定使用第二个变量进行跟踪.不过,我强烈建议不要这样做.只需从外部解码所有内容.
如果你真的不能,那么你最好尝试解码$@并忽略错误.这是不太可能的东西可读,是不是UTF-8将是有效的UTF-8.
# $@ is sometimes encoded. If it's not,
# the following will leave it unchanged.
utf8::decode($@);
print $@;
Run Code Online (Sandbox Code Playgroud)