1. Perl
  2. builtin functions
  3. here

reverse function - reverse array (reverse string)

Use the reverse function to reverse string or array.

# Reverse the characters of a string
$str_reverse = reverse $str;

# Reverse the elements of a array
@array_reverse = reverse @array;

You can also use the reverse function to swap the all keys and values of hash.

%hash_reverse = reverse %hash;

Example

This is an example that reverses the characters of a string.

# Reverse the characters of a string
my $string = 'abc';
$string = reverse($string);

This is an example that reverses the elements of a array.

# Sort the array in reverse order
my @nums = (1, 2, 3);
@nums = reverse @nums;

This is an example that swap all keys and values of a hash using a reverse function.

use strict;
use warnings;

use Data::Dumper;
my %x_to_y = (
  'x1' =>'y1',
  'x2' =>'y2',
  'x3' =>'y3',
);

print "original hash\n";
print Data::Dumper->Dump([\%x_to_y], ['*x_to_y']);
print "\n";

# 1: Swap all keys and values of a hash.
my %y_to_x = reverse %x_to_y;
print "1: Swap the hash key and value\n";
print Data::Dumper->Dump([\%y_to_x], ['*y_to_x']);

Output

original hash
%x_to_y = (
            'x2' => 'y2',
            'x3' => 'y3',
            'x1' => 'y1'
          );

1: Swap the hash key and value
%y_to_x = (
            'y1' => 'x1',
            'y2' => 'x2',
            'y3' => 'x3'
          );

Related Informatrion