7.2. Random File I/O

Perl provides mechanisms for moving to certain positions in files, and reading blocks of a certain size.

seek FILEHANDLE, POSITION, WHENCE sets the filehandle position within the file in bytes. If you specify use Fcntl; at the beginning of your program, then WHENCE can be SEEK_SET for start of file, SEEK_CUR for the current position and SEEK_END for the end of file.

tell FILEHANDLE returns the position of the current file cursor in bytes from the beginning of the file.

read FILEHANDLE, SCALAR, LENGTH reads LENGTH characters from FILEHANDLE into the SCALAR variable.

Here's an example that replaces bytes 64-127 in a file with their rot13 equivalent:

#!/usr/bin/perl

use strict;
use warnings;

use Fcntl;

my $filename = shifg;

open F, "+<$filename"
    or die "Could not open file";

# Read bytes 64-127 into $text
seek(F, 64, SEEK_SET);

my $text;
read(F,$text,64);
# Do the actual rot13'ing with the tr command
$text =~ tr/A-Za-z/N-ZA-Mn-za-m/;
# Write them at poisition 64
seek(F, 64, SEEK_SET);
print F $text
close(F);

Written by Shlomi Fish