【发布时间】:2016-08-04 06:58:14
【问题描述】:
我试图在读取包含无效 UTF-8 的文件(应该包含有效的 UTF-8)时打印警告消息。但是,如果无效数据位于文件末尾,我将无法输出任何警告。以下MVCE 创建了一个包含无效 UTF-8 数据的文件(文件的创建与一般问题无关,只是在此处添加以生成 MVCE):
use feature qw(say);
use strict;
use warnings;
binmode STDOUT, ':utf8';
binmode STDERR, ':utf8';
my $bytes = "\x{61}\x{E5}\x{61}"; # 3 bytes in iso 8859-1: aåa
test_read_invalid( $bytes );
$bytes = "\x{61}\x{E5}"; # 2 bytes in iso 8859-1: aå
test_read_invalid( $bytes );
sub test_read_invalid {
my ( $bytes ) = @_;
say "Running test case..";
my $fn = 'test.txt';
open ( my $fh, '>:raw', $fn ) or die "Could not open file '$fn': $!";
print $fh $bytes;
close $fh;
my $str = '';
open ( $fh, "<:encoding(utf-8)", $fn ) or die "Could not open file '$fn': $!";
$str = do { local $/; <$fh> };
close $fh;
say "Read string: '$str'\n";
}
输出是:
Running test case..
utf8 "\xE5" does not map to Unicode at ./p.pl line 22.
Read string: 'a\xE5a'
Running test case..
Read string: 'a'
在最后一个测试用例中,文件末尾的无效字节似乎被 PerlIO 层 :encoding(utf-8) 默默忽略了。
【问题讨论】: