Table of Contents

Our Own Perl Wiki

Differences from Java


File I/O in Perl

Default file handlers:

Opening a file

open(FILEHANDLE, filename)

Where FILEHANDLE specifes the name for the file handler in which you will refer to your file and filename specifies the location of your file.

In the file name one can specify the various read/write modes.

Example Description
open(FILEHANDLE, <filename) opens the file for reading
open(FILEHANDLE, >filename) opens the file for writing
open(FILEHANDLE, »filename) opens the file for appending
open(FILEHANDLE, +>filename) opens the file for reading and writing
open(FILEHANDLE, +<filename) opens the file for reading and writing
open(FILEHANDLE, +»filename) opens the file for reading and writing

File locking for I/O is provided using the flock() function. It is suggested to do the lock on a seperate file to prevent race conditions.

open(LOCK, ">write.lock")
flock(LOCK, LOCK_EX);
open(DATA, myFile);
#...do work with the DATA file...
close LOCK;
close DATA;

Closing the LOCK handler automatically unlocks the semaphore. One can also use flock(LOCK, LOCK_UN) to do the unlocking specifically. The flock function takes the following operation parameters:

Operation Description
LOCK_SH requests a shared lock for a file, will block until lock is obtained
LOCK_EX requests an exclusive lock for a file, will block until lock is obtained
LOCK_UN unlocks the previously locked file
LOCK_NB should be bitwise 'or'-ed with either LOCK_SH or LOCK_EX and will result in a non-blocking lock