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.>
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...