How to reverse a String and List in Perl| Reverse function

This tutorial shows you how to reverse a string and list in Perl.

Perl reverse function does two things

  • In Scalar Context, It reverses the string into reverse order
  • In List Context, It reverses the list into the reverse list

Perl Reverse Function example

reverse function reverse variable data. Syntax

reverse(variable);

Reverse the data in the variable and returns it

Here is an example

my $str="Hello";
$reverseStr = reverse($str);

print "$reverseStr";

Output:

olleH

How to print the array or list in Reverse order in Perl

To reverse the array in reverse order, Please follow the steps.

  • Declare an array or list with literal syntax
  • pass the array to the reverse function
  • reverse in list context reverse the array in reverse order
  • Return a reverse list
  • Print the list in reverse order
my @number=(1,2,3,4,5);
@reversenumbers = reverse(@number);

print "@reversenumbers";

Output:

5 4 3 2 1

How to Reverse string in Perl with code example

To reverse String in reverse order, Please follow the steps.

  • Declare a string with the literal value
  • pass the string to the reverse function
  • reverse in scalar context reverse the string in reverse order, firstcharacter is changed to the last character, last character to the first character
  • Return a reverse string
  • Print the string in reverse order
my $name="welcome";
$reverseName = reverse($name);

print "$reverseName";

Output:

emoclew