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: $!


Share the Post: