debug.txt"); binmode(D); print D $data; close D; 输-6ren">
gpt4 book ai didi

perl - 使用 ActivePerl 读取二进制文件时出现问题?

转载 作者:行者123 更新时间:2023-12-01 09:38:38 24 4
gpt4 key购买 nike

我正在尝试使用以下代码读取二进制文件:

open(F, "<$file") || die "Can't read $file: $!\n";
binmode(F);
$data = <F>;
close F;

open (D,">debug.txt");
binmode(D);
print D $data;
close D;

输入文件为16M; debug.txt 只有大约 400k。当我在 emacs 中查看 debug.txt 时,最后两个字符是 ^A^C(根据 notepad++ 的 SOH 和 ETX 字符),尽管 debug.txt 中存在相同的模式。文件中的下一行确实有一个 ^O (SI) 字符,我认为这是该特定字符的第一次出现。

如何阅读整个文件?

最佳答案

如果您真的想一次读取整个文件,请使用 slurp 模式。可以通过将 $/(输入记录分隔符)设置为 undef 来打开 Slurp 模式。这最好在一个单独的 block 中完成,这样您就不会将 $/ 弄乱其他代码。

my $data;
{
open my $input_handle, '<', $file or die "Cannot open $file for reading: $!\n";
binmode $input_handle;
local $/;
$data = <$input_handle>;
close $input_handle;
}

open $output_handle, '>', 'debug.txt' or die "Cannot open debug.txt for writing: $!\n";
binmode $output_handle;
print {$output_handle} $data;
close $output_handle;

使用 my $data 作为词法,使用 our $data 作为全局变量。

关于perl - 使用 ActivePerl 读取二进制文件时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3502904/

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