How to read the entire contents of a file directly into an array with Perl
Question: How do I read the entire contents of a file directly into an array with Perl?
Answer:
You'll generally want to read an entire file into a Perl array when you're concerned about the performance of your Perl program. It's often much faster to read the contents of a file into an array, and then work with the array, instead of constantly opening, reading, and closing the file to read the information you want.
Reading the entire contents of a text file into a Perl array is easy. Here's how to read the contents of the standard Unix /etc/passwd
file into a Perl array named passwdRecs
:
open (FILE, '/etc/passwd');
chomp (@passwdRecs = (<FILE>));
close(FILE);
At this point, the array (or 'list', if you prefer) named passwdRecs
contains the entire contents of the /etc/passwd
file, with the trailing newline characters chomp'ed off the end of each string in the array.
A simple, complete Perl example
Here's a complete example showing how to read the /etc/passwd
file into a Perl array. Just for kicks, each line of the file is then printed, preceded by the line number:
#!/usr/bin/perl
open (FILE, '/etc/passwd');
#-----------------------------------------------------#
# read the entire file into the array named 'lines' #
#-----------------------------------------------------#
chomp (@lines = (<FILE>));
close(FILE);
#--------------------------------------------------------#
# print each line, with the line number printed before #
# the actual line #
#--------------------------------------------------------#
$i = 1;
foreach $line (@lines) {
print "$i| $line\n";
$i++;
}
This isn't an extremely useful program by itself, but it demonstrates the basic technique of (a) reading the file into an array and (b) looping through the array contents to generate the information you want.
Be careful about reading very large files into Perl arrays, especially on systems without much memory (RAM). But if you do have the memory available, read the file into an array to improve your performance.
What's Related
We also have our own devdaily.com Perl FAQ list, which keeps growing every year.