Perl | File Handling Introduction
Last Updated :
20 Feb, 2023
In Perl, file handling is the process of creating, reading, writing, updating, and deleting files. Perl provides a variety of built-in functions and modules that make it easy to work with files. Here's an introduction to file handling in Perl:
File modes:
When opening a file in Perl, you need to specify a file mode, which determines how the file can be accessed. There are three main file modes:
- Read mode (<): Opens the file for reading. The file must already exist.
- Write mode (>): Opens the file for writing. If the file does not exist, it will be created. If the file already exists, its contents will be truncated.
- Append mode (>>): Opens the file for writing, but appends new data to the end of the file instead of overwriting its contents. If the file does not exist, it will be created.
File handling functions:
Here are some of the most commonly used built-in file-handling functions in Perl:
- open(): Opens a file and returns a file handle.
- close(): Closes a file handle.
- print(): Writes data to a file.
- read(): Reads data from a file.
- seek(): Moves the file pointer to a specific location in the file.
- tell(): Returns the current position of the file pointer.
- stat(): Returns information about a file, such as its size, owner, and permissions.
File handling modules:
In addition to the built-in file-handling functions, Perl also provides a number of modules that can make file handling easier and more efficient. Here are some of the most commonly used file-handling modules in Perl:
- File::Basename: Provides functions for working with file paths, such as extracting the filename or directory from a path.
- File::Copy: Provides functions for copying files.
- File::Find: Provides functions for searching a directory tree for files that match a pattern.
- File::Path: Provides functions for creating and removing directories.
- File::Spec: Provides functions for working with file paths that are platform-independent.
Overall, file handling is an important aspect of programming in Perl. Whether you need to read data from a file, write data to a file, or perform more complex file operations, Perl provides a variety of tools and modules to help you get the job done.
In Perl, 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.
The three basic FileHandles in Perl are STDIN, STDOUT, and STDERR, which represent Standard Input, Standard Output, and Standard Error devices respectively. File Handling is usually done through the open function.
Syntax: open(FileHandle, Mode, FileName);
Parameters:
- FileHandle- The reference to the file, that can be used within the program or until its closure.
- Mode- Mode in which a file is to be opened.
- FileName- The name of the file to be opened.
Also, Mode and FileName can be clubbed to form a single expression for opening.
Syntax: open(FileHandle, Expression);
Parameters:
- FileHandle- The reference to the file, that can be used within the program or until its closure.
- Expression- Mode and FileName clubbed together.
The FileHandle is closed using the close function.
Syntax: close(FileHandle);
Parameters:
- FileHandle- The FileHandle to be closed.
Reading from and Writing to a File using FileHandle
Reading from a FileHandle can be done through the print function.
Syntax: print(<FileHandle>);
Parameters:
- FileHandle- FileHandle opened in read mode or a similar mode.
Writing to a File can also be done through the print function.
Syntax: print FileHandle String
Parameters:
- FileHandle- FileHandle opened in write mode or a similar mode.
- String- The String to be inserted in the file.
Different Modes in File Handling
Mode | Explanation |
---|
"<" | Read Only Mode |
---|
">" | Creates file (if necessary), Clears the contents of the File and Writes to it |
---|
">>" | Creates file (if necessary), Appends to the File |
---|
"+<" | Reads and Writes but does NOT Create |
---|
"+>" | Creates file (if necessary), Clears, Reads and Writes |
---|
"+>>" | Creates file (if necessary), Reads and Appends |
---|
Examples: Consider a file Hello.txt containing the string "Welcome to GeeksForGeeks!!!" initially.
- Mode = "<" This is read-only Mode. This mode is used to Read the content line by line from the file.
Perl
#!/usr/bin/perl
# Opening a File in Read-only mode
open(r, "<", "Hello.txt");
# Printing content of the File
print(<r>);
# Closing the File
close(r);
Output:
Mode = ">" This is write-only Mode. Original contents of the File are cleared once it is opened in this Mode. It creates a new File with the same name, if one is not found.
Perl
#!/usr/bin/perl
# Opening File Hello.txt in Read mode
open(r, "<", "Hello.txt");
# Printing the existing content of the file
print("Existing Content of Hello.txt: " . <r>);
# Opening File in Write mode
open(w, ">", "Hello.txt");
# Set r to the beginning of Hello.txt
seek r, 0, 0;
print "\nWriting to File...";
# Writing to Hello.txt using print
print w "Content of this file is changed";
# Closing the FileHandle
close(w);
# Set r to the beginning of Hello.txt
seek r, 0, 0;
# Print the current contents of Hello.txt
print("\nUpdated Content of Hello.txt: ".<r>);
# Close the FileHandle
close(r);
- Output:

- Mode=">>" This is Append Mode. Original content of the File is not cleared when it is opened in this Mode. This Mode cannot be used to overwrite as the String always attaches at the End. It creates a new File with the same name, if one is not found.
Perl
#!/usr/bin/perl
# Opening File Hello.txt in Read mode
open(r, "<", "Hello.txt");
# Printing the existing content of the file
print("Existing Content of Hello.txt: " . <r>);
# Opening the File in Append mode
open(A, ">>", "Hello.txt");
# Set r to the beginning of Hello.txt
seek r, 0, 0;
print "\nAppending to File...";
# Appending to Hello.txt using print
print A " Hello Geeks!!!";
# close the FileHandle
close(A);
# Set r to the beginning of Hello.txt
seek r, 0, 0;
# Print the current contents of Hello.txt
print("\nUpdated Content of Hello.txt: ".<r>);
# Close the FileHandle
close(r);
Output:

- Mode = "+<" This is Read-Write Mode. This can be used to overwrite an existing String in File. It cannot create a new File.
Perl
#!/usr/bin/perl
# Open Hello.txt in Read-Write Mode
open(rw, "+<", "Hello.txt");
# Print original contents of the File.
# rw is set to the end.
print("Existing Content of Hello.txt: ".<rw>);
# The string is attached at the end
# of the original contents of the file.
print rw "Added using Read-Write Mode.";
# Set rw to the beginning of the File for reading.
seek rw, 0, 0;
# Printing the Updated content of the File
print("\nUpdated contents of Hello.txt: ".<rw>);
# Close the FileHandle
close(rw);
Output:
Mode = "+>" This is Read-Write Mode. The difference between "+<" and "+>" is that "+>" can create a new File, if one with the name is not found, but a "+<" cannot.
Perl
#!/usr/bin/perl
# Opening File Hello.txt in Read mode
open(r, "<", "Hello.txt");
# Printing the existing content of the file
print("Existing Content of Hello.txt: " . <r>);
# Closing the File
close(r);
# Open Hello.txt in Read-Write Mode
open(rw, "+>", "Hello.txt");
# Original contents of the File
# are cleared when the File is opened
print("\nContents of Hello.txt gets cleared...");
# The string is written to the File
print rw "Hello!!! This is updated file.";
# Set rw to the beginning of the File for reading.
seek rw, 0, 0;
print("\nUpdated Content of Hello.txt: " .<rw>);
# Closing the File
close(rw);
Output:
Mode = "+>>" This is Read-Append Mode. This can be used to Read from a File as well as Append to it. A new File with same name is created, if one is not Found.
Perl
# Open Hello.txt in Read-Append Mode
open(ra, "+>>", "Hello.txt");
# Set ra to the beginning of the File for reading.
seek ra, 0, 0;
# Original content of the File
# is NOT cleared when the File is opened
print("Existing Content of the File: " . <ra>);
print "\nAppending to the File....";
# The string is appended to the File
print ra "Added using Read-Append Mode";
# Set ra to the beginning of the File for reading.
seek ra, 0, 0;
# Printing the updated content
print("\nUpdated content of the File: " . <ra>);
# Closing the File
close(rw);
Output:

- Open a FileHandle to write i.e. ">", ">>", "+<", "+>" or "+>>".
- Select the FileHandle using select function.
Similar Reads
Basics
Perl is a general purpose, high level interpreted and dynamic programming language. Perl supports both the procedural and Object-Oriented programming. Perl is a lot similar to C syntactically and is easy for the users who have knowledge of C, C++. Since Perl is a lot similar to other widely used lan
3 min read
Perl is a general-purpose, high level interpreted and dynamic programming language. It was developed by Larry Wall, in 1987. There is no official Full form of the Perl, but still, the most used expansion is "Practical Extraction and Reporting Language". Some of the programmers also refer Perl as the
9 min read
Prerequisite: Introduction to Perl Before, we start with the process of Installing Perl on our System, whether it be Windows, Linux or Macintosh. We must have first-hand knowledge of What the Perl Language is and what it actually does?. Perl is a general purpose, high level interpreted and dynamic p
3 min read
Perl is a general purpose, high level interpreted and dynamic programming language. Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. Perl supports both the procedural and
10 min read
Perl programming language is exclusively designed for text processing purposes. Its abbreviation denotes Practical Extraction and Report Language. It is compatible on various platforms, such as Windows, Mac OS, and almost all versions of UNIX. Hello World! program in every programming language gives
3 min read
Arrays & Lists
In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Example: @number = (50, 70, 46); @names = ("Geeks", "For",
6 min read
In Perl, array is a special type of variable. The array is used to store the list of values and each object of the list is termed as an element. Elements can either be a number, string, or any type of scalar data including another variable. Arrays can store any type of data and that data can be acce
3 min read
Perl provides various inbuilt functions to add and remove the elements in an array. .string-table { font-family: arial, sans-serif; border-collapse: collapse; border: 1px solid #5fb962; width: 100%; } .string-table td, th { background-color: #c6ebd9; border: 1px solid #5fb962; text-align: left; padd
3 min read
Introduction to Lists A list is a collection of scalar values. We can access the elements of a list using indexes. Index starts with 0 (0th index refers to the first element of the list). We use parenthesis and comma operators to construct a list. In Perl, scalar variables start with a $ symbol wher
4 min read
OOP Concepts
Object-oriented programming: As the name suggests, Object-Oriented Programming or OOPs refers to languages that uses objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind to
7 min read
In this modern world, where the use of programming has moved to its maximum and has its application in each and every work of our lives, we need to adapt ourselves to such programming paradigms that are directly linked to the real-world examples. There has been a drastic change in the competitivenes
6 min read
Perl is an Objected Oriented, dynamic and interpreter based programming language. In object-oriented programming, we have three main aspects, which are, object, class, and methods. An object is a data type which can be specifically called as an instance of the class to which it belongs. It can be a
6 min read
Methods are used to access and modify the data of an object. These are the entities which are invoked with the use of objects of a class or a package itself. Methods are basically a subroutine in Perl, there is no special identity of a method. Syntax of a method is the same as that of a subroutine.
5 min read
Constructors Constructors in Perl subroutines returns an object which is an instance of the class. In Perl, the convention is to name the constructor "new". Unlike many other OOPs, Perl does not provide any special syntax for constructing an object. It uses Data structures(hashes, arrays, scalars) t
4 min read
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. When a method in a subclass has the same name, same parameters or signat
6 min read
Inheritance is a key concept in object-oriented programming that allows you to define a new class based on an existing class. The new class, called a subclass or derived class, inherits all of the properties and methods of the existing class, called the superclass or base class, and can also define
7 min read
Polymorphism is the ability of any data to be processed in more than one form. The word itself indicates the meaning as poly means many and morphism means types. Polymorphism is one of the most important concepts of object-oriented programming languages. The most common use of polymorphism in object
4 min read
Encapsulation in Perl is the process of wrapping up of data to protect it from the outside sources which need not have access to that part of the code. Encapsulation is a part of the Object-oriented programming, it is used to bind the data and the subroutines that are used to manipulate that data. I
6 min read
File Handling
In Perl, file handling is the process of creating, reading, writing, updating, and deleting files. Perl provides a variety of built-in functions and modules that make it easy to work with files. Here's an introduction to file handling in Perl: File modes:When opening a file in Perl, you need to spec
7 min read
A filehandle is an internal Perl structure that associates a physical file with a name. All filehandles have read/write access, so once filehandle is attached to a file reading/writing can be done. However, the mode in which file handle is opened is to be specified while associating a filehandle. Op
4 min read
A filehandle is a variable that is used to read and write to a file. This filehandle gets associated with the file. In order to write to the file, it is opened in write mode as shown below: open (FH, â>â, âfilename.txtâ); If the file is existing then it truncates the old content of file with the
3 min read
Perl was originally developed for the text processing like extracting the required information from a specified text file and for converting the text file into a different form. These operations can be performed by the use of various inbuilt file functions. Example: Perl #!/usr/bin/perl # Opening a
2 min read