File handling in Perl is used to read data from an external file or to write data into an external file. This is very useful as it provides a platform to permanently store and retrieve data from files.
A FileHandle associates a name to an external file, that can be used until the end of the program or until the FileHandle is closed. In short, a FileHandle is like a connection that can be used to modify the contents of an external file and a name is given to the connection (the FileHandle) for faster access and ease.
Input and output functions (I/O functions) are an integral part of file handling and below are the main I/O functions explained with examples.
This function reads one line from the FILEHANDLE which must be referred to by the given expression. For every function call, the next line of the file is read. This can be repeated till the end of file is reached. In order to use a filehandle directly, it must be passed as a typeglob.
This function is used to set the format of reading and writing of FILEHANDLE to binary. When a file is written as a binary it doesn’t have an end of file character. Since the data is read and written in binary, the execution is faster and more efficient as the data doesn’t have to be converted by the machine and is directly understandable.
This function is used to read a desired number of characters from a file during execution, i.e, it can be used to read a block of buffered information. It is also used to read binary data from files.
read(FILEHANDLE, SCALAR, LENGTH)
print() is one of the most important I/O functions in perl. It is used to output data into a file from the console.
print FILEHANDLE LIST
This will write “These are the file contents” into the file
This function is used to change the position of the file pointer to the desired position. The position here can also be changed respectively to another specified position (WHENCE).
seek(FILEHANDLE, POSITION, WHENCE)
Here WHENCE is used to specify a position respective to which the pointer is moved.
a) WHENCE = 0, signifies that the pointer must start at the beginning of the file.
b) WHENCE = 1, signifies that the pointer must start at the current position of the file.
c) WHENCE = 2, signifies that the pointer must start at the end of the file.
The position of the pointer will be set to the specified position.
This function is used to get the position of the pointer in the file from the program.
This is so because initially the pointer is at 0 position but after reading a character it moves to position 1.
When we open a file, we associate a FILEHANDLE with an external file. Thus, when we finish using the file, we must disassociate the FILEHANDLE from the file and for this, the close() function is used. This flushes the FILEHANDLE’s buffers.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.