How can I create a binary file in Perl?

后端 未结 3 1426
广开言路
广开言路 2020-12-30 19:20

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.

3条回答
  •  一个人的身影
    2020-12-30 20:15

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

    In the above example, the 's' tells it to output a short (16 bits), and the '<' forces it to little-endian mode.

    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.

提交回复
热议问题