ADVERTISEMENT
ADVERTISEMENT

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)

ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.