如何在 Perl 中创建二进制文件? [英] How can I create a binary file in Perl?
问题描述
例如,我想创建一个名为 sample.bin
的文件,并输入一个数字,比如 255,这样 255 在文件中保存为 little-endian,FF 00.或 3826 为F2 0E.
For example, I want to create a file called sample.bin
and put a number, like 255, so that 255 is saved in the file as little-endian, FF 00. Or 3826 to F2 0E.
正如 perldoc 所说,我尝试使用 binmode.
I tried using binmode, as the perldoc said.
推荐答案
Perl pack 函数将根据模板返回二进制"数据.
The Perl pack function will return "binary" data according to a template.
open(my $out, '>:raw', 'sample.bin') or die "Unable to open: $!";
print $out pack('s<', 255);
close($out);
在上面的例子中,的'
告诉它输出一个short
(16位),而'<'
强制它进入小端模式.
In the above example, the 's'
tells it to output a short
(16 bits), and the '<'
forces it to little-endian mode.
此外,':raw'
在对 open
的调用中告诉它在重要的平台上将文件句柄置于二进制模式(相当于使用 <代码>binmode).PerlIO 手册页提供了有关以不同格式执行 I/O 的更多信息.
In addition, ':raw'
in the call to open
tells it to put the filehandle into binary mode on platforms where that matters (it is equivalent to using binmode
). The PerlIO manual page has a little more information on doing I/O in different formats.
这篇关于如何在 Perl 中创建二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!