gpt4 book ai didi

perl - 当我使用 open ':std' , ':encoding(UTF-8)' ; 时,为什么 File::Slurp 得到错误的 UTF8 字符?

转载 作者:行者123 更新时间:2023-12-05 09:07:22 28 4
gpt4 key购买 nike

我在 Ubuntu 上有一个 Perl 5.30.0 程序,其中 File::Slurpopen ':std', ':encoding(UTF-8)' 导致 UTF8 无法正确读取:

use strict;
use warnings;
use open ':std', ':encoding(UTF-8)';
use File::Slurp;

my $text = File::Slurp::slurp('input.txt');
print "$text\n";

“input.txt”是具有此内容(无 BOM)的 UTF8 编码文本文件:

ö

当我运行它时,ö 显示为 ö。只有当我删除 use open... 行时,它才会按预期工作并且 ö 打印为 ö

当我像下面这样手动读取文件时,一切都按预期工作,我确实得到了 ö:

$text = '';
open my $F, '<', "input.txt" or die "Cannot open file: $!";
while (<$F>) {
$text .= $_;
}
close $F;
print "$text\n";

为什么会这样?去这里的最佳方式是什么? open pragma 是否已过时,还是我遗漏了其他内容?

最佳答案

与许多 pragma 一样,[1] use open 的效果是词法范围的。[2] 这意味着它只影响找到它的 block 或文件的其余部分。这样的 pragma 不会影响其范围之外的函数中的代码,即使它们是从其范围内调用的。

您需要将解码流的愿望传达给 File::Slurp。这不能使用 slurp 来完成,但可以通过其 binmode 参数使用 read_file 来完成。

use open ':std', ':encoding(UTF-8)';  # Still want for effect on STDOUT.
use File::Slurp qw( read_file );

my $text = read_file('input.txt', { binmode => ':encoding(UTF-8)' });

更好的模块是File::Slurper .

use open ':std', ':encoding(UTF-8)';  # Still want for effect on STDOUT.
use File::Slurper qw( read_text );

my $text = read_text('input.txt');

File::Slurper 的 read_text 默认使用 UTF-8 解码。


没有模块,你可以使用

use open ':std', ':encoding(UTF-8)';

my $text = do {
my $qfn = "input.txt";
open(my $F, '<', $qfn)
or die("Can't open file \"$file\": $!\n");
local $/;
<$fh>
};

当然,这不像早期的解决方案那么清晰。


  1. 其他值得注意的示例包括使用 VERSION使用 strict使用警告使用功能使用 utf8
  2. :std 对 STDIN、STDOUT 和 STDERR 的影响是全局的。

关于perl - 当我使用 open ':std' , ':encoding(UTF-8)' ; 时,为什么 File::Slurp 得到错误的 UTF8 字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64974031/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com