Subscribe to the RSS feed for the devdaily.com blog
Page not found (404 error) | alvinalexander.com

Page not found (404 error)

I’m sorry, the URL you are looking for can't be found.

This may be because I’ve made several significant changes to the website lately. If you want to take a few moments to search for the document you were looking for, you can try the Search Page here.

(I am trying to fix all the links I have broken, but it takes time.)

Thank you for your patience, and have a nice day!

Alvin Alexander
Owner, Editor, Link-breaker, Repairman,
AlvinAlexander.com


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.


devdaily logo