如何在Perl中创建二进制文件?

时间:2012-02-29 06:13:31

标签: perl

od -x test显示:

0000000 457f 464c 0102 0001

现在我想用Perl创建这样的文件。

open FH,'>','test_1';
#syswrite(FH,0x457f464c01020001); # not work
print FH 0x457f464c01020001;      # not work

如何在Perl中创建二进制文件?

4 个答案:

答案 0 :(得分:7)

要创建二进制文件,请使用

open (my $fh, '>:raw', $qfn)

放置

45 7f 46 4c 01 02 00 01

在该文件中,可以使用以下任何一种方法:

# Starting with a string of those bytes.
print $fh "\x45\x7f\x46\x4c\x01\x02\x00\x01";

# Starting with a hex representation of the file.
print $fh pack('H*', '457f464c01020001');

# Starting with the bytes.
print $fh map chr, 0x45, 0x7f, 0x46, 0x4c, 0x01, 0x02, 0x00, 0x01;

# Starting with the bytes.
print $fh pack('C*', 0x45, 0x7f, 0x46, 0x4c, 0x01, 0x02, 0x00, 0x01);

答案 1 :(得分:2)

open(my $out, '>:raw', 'test_1.bin') or die "Unable to open: $!";
print $out pack('s<',255) ;
close($out);

你也可以查看perl pack函数here

答案 2 :(得分:1)

print FH pack 'H*', '457f464c01020001'

答案 3 :(得分:0)

print FH "\x45\x7f\x46\x4c\x01\x02\x00\x01"是另一种方式。有关字符串中可用转义序列的更多信息,请参阅Quote and Quote-like Operators in perlop\x与C中的工作方式类似......但Perl的语法扩展超出\xff

相关问题