How to create or write in a file using Perl?

Here, we will learn how to write data in a file using Perl programming language?
Submitted by Godwill Tetah, on December 12, 2020

There will be a text file with extension .txt. We will use the Perl inbuilt function known as File Handle.

File Handle function gives us the ability to open, read and write in a file. But there are still Perl third party modules or functions which could be used for more complex tasks.

We will code a tiny program that will write some text into a file. If the file is not found, it creates a new file.

Program/Source Code:

File name: index.pl

open( FH, ">index.txt" );
$var = "hello, welcome to perl world";
print FH $var;
close FH;

Output:

Create or write in a file using Perl (1)

Create or write in a file using Perl (2)

The code can me modified such that the user inputs what he wants to write in the file directly in the console. See below,

index.pl

We are just going to modify one line of code. Where what to be written is put, we will remove it and put <>

open( FH, ">index.txt" );
$var = <>;
print FH $var;
close FH;

Output:

Create or write in a file using Perl (3)

As you see above, the user is given the opportunity to write his mind.

Create or write in a file using Perl (4)

Now let us check the file.

Create or write in a file using Perl (5)



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.