File Handling in Perl


File Handling Perl – AyeSir.org


A FILEHANDLE is a temporary alias name given to a file that we will be using in perl script. Major functions used for this: Open (), Read (), Write (), Close ().

Open File

open (FILENAME, “< xyz.txt”);

Here the FILEHANDLE “FILENAME” will be associated with the file “xyz.txt”. This FILEHANDLE is then used to read from the file.

Modify File

There are various modes of operation: read (<), write (>), append (>>), read/write [(+<) or (+>)], read/append (+>>)

open (FILE, “< abc.log”); — reads the file

open (FILE, “>abc.log”); — writes in to the file

open (FILE, “>> abc.log”); — appends the file

open (FILE, “< abc.log” or die $!); — if the file abc.log does not exist or it is not readable then the script will die with display of whatever message stored in $!

  • +> –opens the file in read/write mode and also creates the file if does not exist. It also delete/truncate existing file.

Write to a File

open (FH, “> abc.txt”); — here file handle is opened in write mode

print FH $data; — content of $data will be written to the file handle FH. Here $ data can also be a scalar, a list or a hash.

Close File

close FILE;

close FH or die $! – here the close command may error out while trying to close a closed file. So it will die with displaying message stored in $!

Input from STDIN

<STDIN> is used for reading from the standard input in perl.

$data = <STDIN>;



Output to STDOUT

Print and printf function are used to display result in standard output.

print 2+3, “Hi There” – prints 5Hi There

STDIN and STDOUT can also be opened with other FILEHANDLE

open (FH_IN, “– “);

print FH_IN, “Standard input is opened with name: FH_IN”;

open (FH_OUT, “> – “);

print FH_OUT “Standard Output is opened with the name: FH_OUT”;

Deleting File

unlink (“/abc/xyz/filename.log”);

Position of FILEHANDLE

Tell () function is used to return the current position of FILEHANDLE in bytes. If not specified it assumes last line as the position.

$x = tell FILEHANDLE

print “$x”;

Seek () function is used to position the file pointer to a specific location based on the bytes specified . This works like cut command in unix.

Syntax: seek FH, bytes, WHENCE – here WHENCE is the position of file pointer from where specified bytes of data will be fetched.

Seek FILE, 5,0 – this reads file after first 5 bytes