这是否正常工作?有些错误信息已经解码,有些需要解码才能得到正确的输出。
#!/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( $@ );
}
}
最佳答案
Am I using utf8::is_utf8 correctly?
没有。 utf8::is_utf8
的任何使用都是不正确的,因为你永远不应该使用它!使用 utf8::is_utf8
猜测字符串的语义是所谓的 The Unicode Bug 的实例。 . utf8::is_utf8
除了在调试 Perl 或 XS 模块时检查变量的内部状态外,没有任何用处。
它不表示变量中的值是否使用 UTF-8 编码。事实上,这是不可能可靠地知道的。例如,"\xC3\xA9"
是否生成使用 UTF-8 编码的字符串?好吧,没有办法知道!这取决于我的意思是 "é"
、"é"
还是完全不同的东西。
如果变量可能同时包含编码和解码字符串,则由您决定使用第二个变量来跟踪它。不过,我强烈建议不要这样做。只需解码从外部传入的所有内容。
如果你真的不能,你最好尝试解码 $@
并忽略错误。它是 very unlikely不是 UTF-8 的可读内容将是有效的 UTF-8。
# $@ is sometimes encoded. If it's not,
# the following will leave it unchanged.
utf8::decode($@);
print $@;
关于perl - 我正确使用 utf8::is_utf8 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14579560/