Handling binary data

If you are opening a file which contains binary data, you probably don't want to read it in a line at a time using while (<>) { }, as there's no guarantee that there will be any line breaks in the data.

Instead, we use read() to read a certain number of bytes from a file handle.

read() is documented on page 202 of the Camel book, or by using perldoc -f read.

read() takes the following arguments:

#!/usr/bin/perl -w

use strict;

my $image = "picture.gif";

open (IMAGE, $image) or die "Can't open image file: $!";
open (OUT, ">backup/$image") or die "Can't open backup file: $!";

my $buffer;

binmode IMAGE;

while (read IMAGE, $buffer, 1024) {
        print OUT $buffer;
}

close IMAGE;
close OUT;

Note

If you are using Windows, DOS, or some other types of systems, you may need to use binmode() to make sure that certain linefeed characters aren't translated when Perl reads a file in binary mode. While this is not needed on Unix systems, it's a good idea to use it anyway to enhance portability.