The Wayback Machine - https://web.archive.org/web/20240927184618/https://www.geeksforgeeks.org/perl-writing-to-a-file/
Open In App

Perl | Writing to a File

Last Updated : 07 Mar, 2019
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 new content. Otherwise a new file will be created and content will be added.

print() function

print() function is used to write content to a file.

Syntax: print filehandle string

Here, filehandle is associated to the file at the time of opening the file and string holds the content to be written to the file.

Example :




# Opening file Hello.txt in write mode
open (fh, ">", "Hello.txt");
  
# Getting the string to be written
# to the file from the user
print "Enter the content to be added\n";
$a = <>;
  
# Writing to the file
print fh $a;
  
# Closing the file
close(fh) or "Couldn't close the file"; 


Before Writing to File:

Executing Code to Write:

Updated File:

Here is how the program works:
Step 1: Opening file Hello.txt in write mode.
Step 2: Getting the text from the standard input keyboard.
Step 3: Writing the string stored in ‘$a’ to the file pointed by filehandle ‘fh’
Step 4: Closing the file.
 
Copying Content from one file to another:

Before Code Execution:
Source File:

Destination File:

Example :
Example below reads the content from the source file and writes it to destination file.




# Source File 
$src = 'Source.txt';
  
# Destination File
$des = 'Destination.txt';
  
# open source file for reading
open(FHR, '<', $src);
   
# open destination file for writing
open(FHW, '>', $des); 
   
print("Copying content from $src to $des\n");
while(<FHR>)
{
   print FHW $_; 
}
   
# Closing the filehandles
close(FHR);
close(FHW);
   
print "File content copied successfully!\n";


Executing Code:

Updated Destination File:

Here is how the program works:-
Step 1: Opening 2 files Source.txt in read mode and Destination.txt in write mode.
Step 2: Reading the content from the FHR which is filehandle to read content while FHW is a filehandle to write content to file.
Step 3: Copying the content with the use of print function.
Step 4: Close the conn once reading file is done.
 

Error Handling and Error Reporting

There are two ways in which Errors can be handled

  • Throw an exception if file cannot be opened (Handling an error)
  • Give a warning if file cannot be opened and continue running (Error reporting)

Throw an Exception (Using Die Function)
When filehandle could not be assigned a valid file pointer at that time die gets executed printing the message and kills the current program.
Example :




# Initializing filename  
$filename = 'Hello.txt'; 
# $filename = 'ello.txt';
  
# Prints an error and exits 
# if file not found 
open(fh, '<', $filename) or 
     die "Couldn't Open file $filename"; 


In the above code when File exists it simply gets executed with no errors but if file doesn’t exists then it generates an error and code terminates.

Give a warning (Using warn function)
When filehandle could not be assigned a valid file pointer it just prints warning message using warn function and keeps running.
Example :




# Initializing filename 
$filename = 'GFG.txt'; 
  
# Opening a file and reading content 
if(open(fh, '<', $filename)) 
{ 
    while(<fh>) 
    { 
        print $_; 
    } 
} 
  
# Executes if file not found 
else
{ 
  warn "Couldn't Open a file $filename"; 
} 


When File exists:

When File doesn’t exists:



Previous Article
Next Article

Similar Reads

Perl | Basic Syntax of a Perl Program
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 Object-Oriented programming. Perl is a lot similar
10 min read
Modes of Writing a Perl Code
Perl is a general purpose, high level interpreted and dynamic programming language. Perl supports both the procedural and Object-Oriented programming. At the beginning level, Perl was developed only for the system management and text handling but in later versions, Perl got the ability to handle regular expressions, and network sockets, etc. Since
6 min read
Perl | Searching in a File using regex
Prerequisite: Perl | Regular Expressions Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to host language and are not the same as in PHP, Python, etc. Sometimes these are termed as "Perl 5 Compatible Regular Expressions". To use the Regex, Bindi
6 min read
Perl | File Locking
File locking, or locking in general, is just one of the various solutions proposed to deal with problems associated with resource sharing. File locking is a method to preserving the security and integrity of any document. The main motive of file locking is allowing people to commit changes to the document without creating a mess of it. When a file
5 min read
Perl | File Test Operators
File Test Operators in Perl are the logical operators which return True or False values. There are many operators in Perl that you can use to test various different aspects of a file. For example, to check for the existence of a file -e operator is used. Or, it can be checked if a file can be written to before performing the append operation. This
3 min read
Perl | Opening and Reading a File
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. Opening a File Open function is used to open a new f
4 min read
Perl | Appending to a File
When a file is opened in write mode using “>”, the content of the existing file is deleted and content added using the print statement is written to the file. In this mode, the writing point will be set to the end of the file. So old content of file remains intact and anything that is written to file using print statement is added to the end of
2 min read
Perl | Reading a CSV File
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. Reading a text file is a very common task in Perl. For example, you often come across reading CSV(Comma-Separated Value) files to extract data and information. A CSV file c
7 min read
Perl | File Upload in CGI
Perl is general-purpose programming language, specially designed for text manipulation and in present time used for various task including system administration, web development, network programming, GUI development, and in other more area. In Perl, CGI(Common Gateway Interface) is a protocol for executing scripts via web requests or in other words
3 min read
Perl | File Handling Introduction
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
7 min read
Perl | Accessing a Directory using File Globbing
In Perl, a directory is used to store values in the form of lists. A directory is quite similar to a file. Just like a file, the directory also allows performing several operations on it. These operations are used for the modification of an existing directory or creation of a new one. A directory can be very easily opened and processed using the bu
2 min read
Perl | Useful File-handling functions
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: #!/usr/bin/perl # Opening a File in Read-only mode open(fh, "<",
2 min read
Perl | File I/O Functions
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. File Handle 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
4 min read
Perl | eof - End of File Function
The eof() function is used to check if the End Of File (EOF) is reached. It returns 1 if EOF is reached or if the FileHandle is not open and undef in all other cases. Syntax: eof(FileHandle) Parameter: FileHandle: used to open the file Returns: 1 if EOF is reached Cases: eof(FileHandle) : Passing FileHandle to eof() function. If File is empty then
2 min read
Perl | chomp() Function
The chomp() function in Perl is used to remove the last trailing newline from the input string. Syntax: chomp(String) Parameters: String : Input String whose trailing newline is to be removed Returns: the total number of trailing newlines removed from all its arguments Example 1: C/C++ Code #!/usr/bin/perl # Initialising a string $string = &quo
2 min read
Perl | Backtracking in Regular Expression
In Perl, a Regular expression(a.k.a regexes or regexps or REs) is a way of describing a set of strings without having to list all strings in your program or simply we can say that it is a sequence of characters that are used for pattern matching. In Perl, regular expressions have different uses: Firstly, they are used in conditionals to determine w
3 min read
Perl | Operators | Set - 1
Operators are the main building block of any programming language. Operators allow the programmer to perform different kinds of operations on operands. In Perl, operators symbols will be different for different kind of operands(like scalars and string). Operators Can be categorized based upon their different functionality: Arithmetic OperatorsRelat
12 min read
Perl | lt operator
'lt' operator in Perl is one of the string comparison operators used to check for the equality of the two strings. It is used to check if the string to its left is stringwise less than the string to its right. Syntax: String1 lt String2 Returns: 1 if left argument is less than the right argument Example 1: #!/usr/local/bin/perl # Initializing Strin
1 min read
Perl | chop() Function
The chop() function in Perl is used to remove the last character from the input string. Syntax: chop(String) Parameters: String : It is the input string whose last characters are removed. Returns: the last removed character. Example 1: #!/usr/bin/perl # Initialising a string $string = "GfG is a computer science portal"; # Calling the chop
1 min read
Perl | rename() Function
rename() function in Perl renames the old name of a file to a new name as given by the user. Syntax: rename(old_file_path, new_file_path) Parameters: old_file_path: path of the old file along with its name new_file_path: path of the new file along with its name Returns 0 on failure and 1 on success Example: #!/usr/bin/perl -w # Calling the rename()
1 min read
Perl | Subroutines or Functions
A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again. In Perl, the terms function, subroutine, and method are the same but in s
2 min read
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Decision Making in programming is similar to decision making in real life. In programming, a certain block of code needs to be executed when some condition is fulfilled. A programming language uses control statements to control the flow of execution of the program based on certain conditions. These are used to cause the flow of execution to advance
6 min read
Perl | Loops (for, foreach, while, do...while, until, Nested loops)
Looping in programming languages is a feature which facilitates the execution of a set of instructions or functions repeatedly while some condition evaluates to true. Loops make the programmers task simpler. Perl provides the different types of loop to handle the condition based situation in the program. The loops in Perl are : for Loop "for" loop
7 min read
Perl | Comparing Scalars
Prerequisite: Scalars in Perl Perl has two types of comparison operator sets. Just like other mathematical operators, instead of performing operations, these operators compare scalars. There are two types of sets of Perl comparison operators. One is for numeric scalar values and one is for string scalar values. Both the types are illustrated in bel
6 min read
Perl | String functions (length, lc, uc, index, rindex)
String in Perl is a sequence of character enclosed within some kinds of quotation marks. Perl string can contain UNICODE, ASCII and escape sequence characters. Perl provides the various function to manipulate the string like any other programming language. Some string functions of Perl are as follows: length() lc() uc() index() rindex() length(): T
4 min read
Perl | Arrays
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", "Geeks"); Array Creation: In Perl programming ever
6 min read
Perl | Data Types
Data types specify the type of data that a valid Perl variable can hold. Perl is a loosely typed language. There is no need to specify a type for the data while using in the Perl program. The Perl interpreter will choose the type based on the context of the data itself. There are 3 data types in Perl as follows: ScalarsArraysHashes(Associative Arra
3 min read
Perl | String Operators
Operators are the foundation of any programming language. Thus, the functionality of Perl programming language is incomplete without the use of operators. A user can define operators as symbols that help to perform specific mathematical and logical computations on operands. String are scalar variables and start with ($) sign in Perl. The String is
4 min read
Perl | Hashes
Set of key/value pair is called a Hash. Each key in a hash structure are unique and of type strings. The values associated with these keys are scalar. These values can either be a number, string or a reference. A Hash is declared using my keyword. The variable name is preceded by the dollar sign($)followed by key under curly braces and the value as
5 min read
Perl | Regular Expressions
Regular Expression (Regex or Regexp or RE) in Perl is a special text string for describing a search pattern within a given text. Regex in Perl is linked to the host language and is not the same as in PHP, Python, etc. Sometimes it is termed as “Perl 5 Compatible Regular Expressions“. To use the Regex, Binding operators like ‘=~‘(Regex Operator) and
2 min read
Article Tags :