Perl read file FAQ: How can I read a file into an array in Perl (Or, Can you share a Perl read file into array example?)
One of the really cool things about Perl is that it’s easy to read a file into a Perl array. This is really handy any time you need to read every line in a file for any reason.
A Perl “read file into array” example
If you want to read a complete text file into a Perl array, you only need one line of code, like this:
@lines = <>;
Assuming your program is named read-file.pl, and you want to read a file named gettysburg-address.txt, all you need to do to read that file from your program is to run your program like this:
perl read-file.pl gettysburg-address.txt
That actually works, but it’s really hard to tell, since the program doesn’t do anything else. So, if I expand the program to two lines, like this:
@lines = <>; print @lines;
and you run the program again, you’ll see the output of this Perl script when you run it, and the output will be all the lines from the file you just read into your Perl array (the @lines
array).
A second Perl “read text file into array” example
I recently wrote a Perl script that reminded me of this Perl “read file” approach. I named my new script rcat
, and it works just like the Linux cat command, except it prints the contents of a file in reverse. Here’s the source code for my Perl rcat
script:
#!/usr/bin/perl # rcat - a perl script to display the contents of a file in reverse order. # author - alvin alexander, alvinalexander.com @lines = <>; print reverse @lines;
As you can see, this is very simple, just two lines of source code (besides the boilerplate first line and comments). This Perl script uses the Perl reverse
function, which I wrote about in my Perl reverse array tutorial.
Summary: My Perl read file into array examples
I hope these Perl “read file into array” examples have been helpful. As you can see, the process is generally straightforward, at least after you’ve seen some examples.