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:
The filehandle to read from
The scalar to put the binary data into
The number of bytes to read
The byte offset to start from (defaults to 0)
#!/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; |
![]() | 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. |