"Perl for Perl Newbies" - Part 4More System FunctionsRandom File I/O

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, WHENCEsets the filehandle position within the file in bytes. If you specify use Fcntl;at the beginning of your program, then WHENCE can be SEEK_SETfor start of file, SEEK_CURfor the current position and SEEK_ENDfor the end of file.

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

read FILEHANDLE, SCALAR, LENGTHreads LENGTHcharacters from FILEHANDLEinto the SCALARvariable.

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 =
shift;

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 position 64
seek(
F,
64, SEEK_SET);
print
F
$text
close(
F);

Written by Shlomi Fish