Perl reverse Function

The reverse function in scalar context concatenates the elements of a list in a string and returns the string with all the characters in an opposite order; in a list context, it returns the list in the reversed order.

You can use the reverse function either in scalar or list context.

The syntax forms of the Perl reverse function are as follows:

@reversedArray = reverse @array;
 
$str = reverse @array;
 
$newStr = reverse $str;
 
$str = reverse;
The reverse function doesn't change the argument.

If you want to keep the result returned by the function, you need to assign it back to a variable.

As you can see, there are at least 4 syntax forms for this function.

The first syntax form is used in a list context.

In a list context, this function is used to reverse the order of an array, returning a resulting array with the elements in an opposite order.

The next three syntax forms are for the scalar context:

  • you can reverse an array into a string: it concatenates the elements of the array and returns a string value with all the characters in an opposite order
  • you can use reverse to get a string with the characters in the opposite order
  • used without argument, it reverses the $_

See the following examples for an exemplification of the syntax forms of Perl reverse function.

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my @array = qw(one two three four);
# list context
 
my @reversedArray = reverse @array;
print "@reversedArray\n";
# it displays: four three two one
 
# scalar contexts
 
my $str = reverse @array;
print "$str\n";
# it displays: ruofeerhtowteno
 
$str = reverse $str;
print "$str\n";
# it displays: onetwothreefour
 
# the next two examples use reverse with $_
 
print scalar reverse, " " foreach (@array);
# it displays: eno owt eerht ruof
print "\n";
 
$_ = "1234";
$_ = reverse;
print;
# it displays: 4321
print "\n";

You can use both the sort and Perl reverse function to sort an array in a descending alphabetical order. By default the sort function compares the ASCII values of the array elements, so if you have an array of numbers you need to use the <=> operator explicitly to get a correct ordered list.

Here's an example:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my @array = qw(13 21 15 175 1 );
@array = reverse sort {$a <=> $b} @array;
 
print "@array\n";
# it displays: 175 21 15 13 1
You can get the same output without using the Perl reverse function by swapping the $a and $b special variables: 
@array = sort {$b <=> $a} @array;
If your array contains strings as elements, you can omit the cmp operator and the above line of code will look like this: 
@array = reverse sort @array;

The following example shows you how to invert a hash, by swapping the keys with the values. However, at first ensure yourself that your hash has unique values, otherwise the resulting hash will have fewer elements that the initial one.

Here's an example:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my %hash = (one => 1, two => 2, three => 3, four => 4);
%hash = reverse %hash;
 
foreach my $key (sort {$a <=> $b} keys %hash) {
    print "$key => $hash{$key}, ";
}
print "\n";
# it displays: 1 => one, 2 => two, 3 => three, 4 => four
The Perl reverse function inverts the %hash by swapping the values with the keys.

The foreach statement is used to print the elements of the hash. The keys function returns the keys of the hash unordered, so if you want to print the hash keys in an ascending or descending order, you need to use the sort function.

Because after inverting the hash the keys are numbers, the <=> operator is used. In our example the inverted hash is printed with the keys in an ascending order.

If you want a descending order you need to swap $a with $b in the sort function: $b<=>$a. If you want to sort the hash keys alphabetically, you need to use instead the <=> operator, the cmp operator.

You can use the Perl reverse function to reverse the words of a sentence.

Here's an example:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my $sentence = 'This is about the Perl reverse function';
my @words = split /\s+/, $sentence;
@words = reverse @words;
$sentence = join ' ', @words;
 
print "$sentence\n";
#it displays: function reverse Perl the about is This
The split function will return an array from the $sentence string and the array will be inverted by the reverse function. Next the join function will concatenate the elements of the array into the $sentence variable, using the space delimiter. Finally, the content of the $sentence variable will be printed.

You can write a shorthand version of this code using of $_ special variable:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
$_ = 'This is about the Perl reverse function';
print join(' ', reverse (split)), "\n";
#it displays: function reverse Perl the about is This
Here the split function is used without any argument, therefore $_ will be used as expression and whitespace as separator.

You can build a matrix with three rows and three columns and populate a bi-dimensional array with the matrix elements.

You can emulate a bi-dimensional array from a usual array that has as elements references to other arrays. The Perl reverse function will be used to reverse the order of the columns.

See the code:

#!/usr/local/bin/perl
 
use strict;
use warnings;
 
my @matrix = ( [1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]
         );     
            
foreach my $i (@matrix) {
  foreach my $j (reverse @$i) {
    print "$j ";
  }
  print "\n";
}
To traverse the bi-dimensional array, a nested foreach is used. The @$i is used to dereference the references of the @matrix array.

The output is as follows:

3 2 1
6 5 4
9 8 7
 
An alternative to populate the @matrix array is as follows:
my @rows1 = (1, 2, 3);
my @rows2 = (4, 5, 6);
my @rows3 = (7, 8, 9);
 
my @matrix = (\@rows1, \@rows2, \@rows3);