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

使用ActivePerl读取二进制文件时出现问题?,perl,binaryfiles,activestate,Perl,Binaryfiles,Activestate,我正在尝试使用以下代码读取二进制文件: 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; open(F,如果你真的想一次读取整个文件,请使用slurp模式。可以通过将$/(输入记录分隔符)设置为undef来打开slurp模式。这最好在

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

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;

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

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;
{
打开我的$input\u句柄、、'debug.txt'或die“无法打开debug.txt进行写入:$!\n”;
binmode$output\u句柄;
打印{$output\u handle}$数据;
关闭$output\u句柄;
使用
my$data
作为词法变量,使用
our$data
作为全局变量。

是表达您想要实现的目标的最短方式。它还具有内置的错误检查功能

use File::Slurp qw(read_file write_file);
my $data = read_file($file, binmode => ':raw');
write_file('debug.txt', {binmode => ':raw'}, $data);

以更优雅的方式解决全局变量
$/
问题

use IO::File qw();
my $data;
{
    my $input_handle = IO::File->new($file, 'r') or die "could not open $file for reading: $!";
    $input_handle->binmode;
    $input_handle->input_record_separator(undef);
    $data = $input_handle->getline;
}
{
    my $output_handle = IO::File->new('debug.txt', 'w') or die "could not open debug.txt for writing: $!";
    $output_handle->binmode;
    $output_handle->print($data);
}

我不认为这是关于是否使用slurp模式,而是关于正确处理二进制文件

而不是

$data = <F>;

这将只读取1024字节,因此您必须增加缓冲区或使用循环逐部分读取整个文件。

$data=;gets$data=do{undef$/;};为了促进现代实践而编辑,请参见和的基本原理。@daxim-我想建议进行检查,但我觉得这是OP自己的责任……)如果没有良好的榜样和消除过时的代码,我们就无法进行教学。:)我感觉我刚刚被称为过时:)无论如何,这里的解决方案是取消$/。(此解决方案仍然无法将完整的文件写入debug.txt,但目标是将我的所有数据转换为$data,这对我来说已经足够了。谢谢。不太关心优雅-这是一个快速而肮脏的解决方案。但感谢您的教育。在第二个示例中,为什么要将代码分块本地化?当句柄变量消失时当它超出范围时,附加的文件描述符会自动关闭。裸块是创建此类范围的最直接方法。
read(F, $buffer, 1024);