How can I create a binary file in Perl?

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)