0

我不是一个普通的 Perl 程序员,我在论坛或我的几本书中找不到任何关于此的内容。

我正在尝试使用以下构造将二进制数据写入文件: print filehandle $record

我注意到当遇到 x'0A' 时我的所有记录都会被截断,因此显然 Perl 使用 LF 作为记录结束指示符。如何编写完整的记录,例如使用长度说明符?我也担心 Perl 会篡改其他二进制“非打印文件”。

谢谢弗里茨

4

2 回答 2

2

你想用

open(my $fh, '<', $qfn) or die $!;
binmode($fh);

或者

open(my $fh, '<:raw', $qfn) or die $!;

以防止修改。输出句柄也是如此。


这种“在 0A 处截断”的谈话听起来像是您正在使用readline并期望做一些事情而不是阅读一行。

嗯,实际上,它可以!您只需要告诉readline您希望它读取固定宽度记录。

local $/ = \4096;
while (my $rec = <$fh>) {
   ...
}

另一种选择是使用read.

while (1) {
   my $rv = read($fh, my $rec, 4096);
   die $! if !defined($rv);
   last if !$rv;
   ...
}

于 2013-08-13T13:20:13.597 回答
1

Perl is not "tampering" with your writes. If your records are being truncated when they encounter a line feed, then that's a problem with the code that reads them, not the code that writes them. (Unless the format specifies that line feeds must be escaped, in which case the "problem" with the code writing the file is that it doesn't tamper with the data (by escaping line feeds) and instead writes exactly what you tell it to.)

Please provide a small (but runnable) code sample demonstrating your issue, ideally including both reading and writing, along with the actual result and the desired result, and we'll be able to give more specific help.

Note, however, that \n does not map directly to a single data byte (ASCII character) unless you're in binary mode. If the file is being read or written in text mode, \n could be just a CR, just a LF, or a CRLF, depending on the operating system it's being run under.

于 2013-08-13T12:12:45.827 回答