How to read content from a file using Perl?

Here, we will see how to read the content of a file using Perl programming language?
Submitted by Godwill Tetah, on December 12, 2020

It is obvious that you may need to perform a task which requires working with files. Perl has third party modules which facilitates performing some tasks.

In this tutorial, I will be using an inbuilt Perl function called FILE HANDLE to open and read files.

We will write a tiny program that opens a text file in our project directory, reads the content and prints it out on the console.

Let's get started!

Program/Source Code:

File name: index.pl

#reading file content in Perl

open( FH, "<index.txt" );
@content = <FH>;    # specifying the input of the array is FH.
foreach (@content) {
    print "@content";
}
close FH;

Ensure you have a nonempty file with the name index.txt in your project directory. Even though you can also put the directory of a file if the file is not in your current project directory.

Here's my file and content:

Read content from a file using Perl (1)

Read content from a file using Perl (2)

The code above does the following;

  • Opens a file using the file handle function, FH
  • The parameters of the open command simply take the name of the file in question and the symbol of the operation (mode) you wish to perform. In this case, we used a less than sign < which stands for read.
  • We then create an array where FH is assigned to it. For sure, FH contains the properties of the file.
  • Finally, we then use the foreach loop to get the file content and display.
  • Then close the file.

Output:

Read content from a file using Perl (3)




Comments and Discussions!

Load comments ↻






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