How to reverse an array in Perl using the reverse function

Overview

The reverse function is used to reverse elements of an array in Perl.

Syntax

reverse @arr

Parameters

@arr: This is the array that has elements we want to reverse.

Return value

A new array with elements reversed.

Code example

# create an array
@gnaam = ("Apple","Amazon", "Meta");
@country = ("USA", "France", "Germany");
@letters = ("o", "l", "l", "e","H");
print "Before reversing: \@gnaam = @gnaam\n";
print "Before reversing: \@country = @country\n";
print "Before reversing: \@letters = @letter\n";
# reverse arrays
@gnaamRev = reverse @gnaam;
@countryRev = reverse @country;
@letterRev = reverse @letters;
# push values to the array
print "After Reversing: \@gnaam = @gnaamRev\n";
print "Before reversing: \@country = @countryRev\n";
print "Before reversing: \@letters = @letterRev\n";

Explanation

  • Lines 2-4: We create arrays.
  • Lines 5-7: We print the original array values before reversing them.
  • Lines 10-12: We reverse the array elements using the reverse function and store them into new variables.
  • Lines 15-17: We print the arrays with reversed elements on the console.