How can I create a binary file in Perl?

后端 未结 3 1393
广开言路
广开言路 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:02

    Yes, use binmode

    For your entertainment (if not education) my very first attempt at creating a binary file included binmode STDOUT and the following:

    sub output_word {
        $word = $_[0];
        $lsb  = $word % 256;
        $msb  = int($word/256);
        print OUT chr($lsb) . chr($msb);
        return $word;
    } 
    

    FOR PITY'S SAKE DON'T USE THIS CODE! It comes from a time when I didn't know any better.

    It could be argued I still don't, but it's reproduced here to show that you can control the order of the bytes, even with brain-dead methods, and because I need to 'fess up.

    A better method would be to use pack as Adam Batkin suggested.

    I think I committed the atrocity above in Perl 4. It was a long time ago. I wish I could forget it...

提交回复
热议问题