Blog Archive

Wednesday, November 10, 2010

Handling Binary Files in Perl

http://www.tutorialspoint.com/perl/perl_read.htm


Syntax

read FILEHANDLE, SCALAR, LENGTH, OFFSET

read FILEHANDLE, SCALAR, LENGTH


Definition and Usage

Reads, or attempts to read, LENGTH number of bytes from the file associated with FILEHANDLE into BUFFER. If an offset is specified, the bytes that are read are placed into the buffer starting at the specified offset.

Return Value

  • The number of bytes read or the undefined value.

Example

Try out following example:

#!/usr/bin/perl -w

my($buffer) = "";
open(FILE, "/etc/services") or
die("Error reading file, stopped");
while(read(FILE, $buffer, 100) )
{
print("$buffer\n");
}
close(FILE);

It will produce following result. This is just sanpshot of the result

kerberos_master 751/udp  # Kerberos authentication
kerberos_master 751/tcp # Kerberos authenti
cation


passwd_server 752/udp # Kerberos passwd server


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 '\n' (LF) into '\r\n' (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 "\nCan't open $srcfile for reading: $!\n";
open OUTF, ">$destfile"
or die "\nCan't open $destfile for writing: $!\n";

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: $!\n" if $!;

close OUTF
or die "Can't close $destfile: $!\n";
close INF
or die "Can't close $srcfile: $!\n";
}



No comments:

Post a Comment