Perl: Various ways to read a file

There is only one way to open or close a file usine open() close() function. You'll find lots of cpan modules which will help you to read file, but internally all the modules are using these to functions to open and close files. I'm showing you how can you read a file into array, or string, or anything else. Just few coding helps regarding file operation.

1) Read the whole file content into an array directly.
open(INFILE, "<input.txt"); ## open file handler
my @lines = <INFILE>; ## read into array
close(INFILE); ## close handler


This code will read all the contents from input.txt, and will load into array @lines directly. Later on, you can do whatever operation you need. You have the file on your hand.

2) Read a single line from your input file.
open(INFILE, "<input.txt"); ## open file handler
my $line = <INFILE>; ## read a single line
close(INFILE); ## close handler

Perl interpreter is intelligent enough to understand your need. Since you provided a scalar to file handler, it will return you the current line that the file handler pointing. This case it will return you only the first line.

3) Using a loop, say while(), process each line while reading without using any array.
open(INFILE, "<input.txt"); ## open file handler
while(<INFILE>){
# current line at the variable $_
## process here
}
close(INFILE); ## close handler


If you don't want to use the default $_ variable, that case you can use this loop.
while (my $line = <INFILE>){
print $line;
}


4) Read the whole file content into a string instead of array. I used to use join() function to do this.
open(INFILE, "<input.txt"); ## open file handler
my $file_content = join('', <INFILE>);
close(INFILE); ## close handler


This join function just take the whole file as array, and join each line from the array. A bit tricky, but nothing else.

I think this will cover what you need when you'll do some file operation at perl scripting.

Comments