【问题标题】:How to create binary file in Perl?如何在 Perl 中创建二进制文件?
【发布时间】:2012-02-29 06:13:31
【问题描述】:

od -x test 显示:

0000000 457f 464c 0102 0001

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

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

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

【问题讨论】:

  • 就其价值而言,您的代码确实“有效”,但它并没有达到您想要的效果。它将十六进制表示转换为其内部数字格式(可能在转换中丢失一堆位),然后打印数字的十进制表示。想一想 - 你几乎不希望 print 1; 打印 ctrl-A。

标签: perl


【解决方案1】:

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

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);

【讨论】:

    【解决方案2】:
    open(my $out, '>:raw', 'test_1.bin') or die "Unable to open: $!";
    print $out pack('s<',255) ;
    close($out);
    

    你也可以看看 perl pack 函数here

    【讨论】:

    【解决方案3】:
    打印 FH 包 'H*', '457f464c01020001'

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 2022-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多