How to reverse an array in Perl?

Question

How to reverse an array in Perl?

Reversing an array in Perl is straightforward thanks to Perl's built-in reverse function. This function can be used both in a scalar and list context—so understanding context is important to correctly reverse an array.

Using reverse to reverse an array

To reverse an array, you simply pass the array to the reverse function in list context. This returns the array elements in the opposite order.

Example:

#!/usr/bin/perl
use strict;
use warnings;

my @original = (1, 2, 3, 4, 5);

# Reverse the array
my @reversed = reverse @original;

# Print both arrays to demonstrate
print "Original array: @original\n";
print "Reversed array: @reversed\n";

When you run this code, you should see:


Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1

Explanation of Perl concepts

  • Sigils: In @original and @reversed, the @ indicates these are arrays.
  • Context: The reverse function behaves differently depending on context. In list context (as used here), it returns the reversed list. In scalar context, it concatenates and reverses a string.
  • TMTOWTDI: "There's more than one way to do it" in Perl – while reverse is idiomatic, arrays can also be manipulated manually, though less efficiently.

Common pitfalls

  • Using reverse in scalar context on arrays won’t reverse the array—it will join the elements into a string and reverse the characters.
  • Don’t confuse reverse with sorting; it only reverses the current order.
  • Remember to assign the reversed list to a new array or overwrite the original.

Additional tips

  • To reverse an array in place, you can overwrite the original array:
    @array = reverse @array;
  • reverse has been part of Perl since very early versions, so this works on any Perl 5 release.

In summary, reversing an array in Perl is easily done using the built-in reverse function in list context. It’s a simple yet powerful tool for array manipulation.

Verified Code

Executed in a sandbox to capture real output. • v5.34.1 • 6ms

Tip: edit code and use “Run (Browser)”. Server runs always execute the published, verified snippet.
STDOUT
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1
STDERR
(empty)

Was this helpful?

Related Questions