A Perl reverse array example - How to reverse file contents

Perl reverse array FAQ: Can you show an example of how to reverse a Perl array (reverse the Perl array contents)?

Sure. I just create a Perl script to print the contents of a text file in reverse order. I named this program rcat (for "reverse cat"), and I use it as a helper program with my transport command (a replacement for the Linux cd command). We can use it to demonstrate the Perl "reverse array" technique.

My Perl reverse array example

Here's the source code for my Perl "reverse file contents" program:

#!/usr/bin/perl

# rcat   - a program to display the contents of a file in reverse order.
# author - alvin alexander, devdaily.com.

@lines = <>;
print reverse @lines;

To run this Perl script from the Unix/Linux command line, first save it in a file named rcat, and then make it executable, like this:

chmod +x rcat

After that, assuming you have a file named numbers that has contents like this:

1
2
3
4
5

if you run this command:

rcat numbers

you will see this output:

5
4
3
2
1

Perl reverse array - Discussion

As you can see, the process to reverse a Perl array is pretty simple, and in this case, it makes for a really powerful way to reverse file contents, or more specifically, display the contents of a text file in reverse order. As mentioned, I use it as part of my "transport" program, where I use it to reverse the file that keeps the history of directories you've visited.

As a warning, I haven't tried this Perl reverse array technique with very large files. Because it pulls all the lines of the file you are reversing into memory in the @lines array, as you can imagine, this program will require a fair amount of memory when trying to printed the reversed the contents of a large file.