devxlogo

Handling Binary Files in Perl

Handling Binary Files in Perl

For some reason, there exists a common misconception that there is no cross-platform, built-in way in Perl to handle binary files. The copy_file code snippet below illustrates that Perl handles such tasks quite well. The trick is to use “binmode” on both the input and output files after opening them. “Binmode” switches files to binary mode, which for the input file means it won’t stop reading at the first “end of text file” character (^Z in win/dos); for the output file binmode means it won’t translate ‘
‘ (LF) into ‘
‘ (CRLF) when printing. In this way the files get copied byte for byte.

sub copy_file {  my ($srcfile, $destfile) = @_;  my $buffer;  open INF, $srcfile    or die "
Can't open $srcfile for reading: $!
";  open OUTF, ">$destfile"    or die "
Can't open $destfile for writing: $!
";  binmode INF;  binmode OUTF;  while (    read (INF, $buffer, 65536)	# read in (up to) 64k chunks, write    and print OUTF $buffer	# exit if read or write fails  ) {};  die "Problem copying: $!
" if $!;  close OUTF    or die "Can't close $destfile: $!
";  close INF    or die "Can't close $srcfile: $!
";}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist