Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
perl
string

How to reverse a string in Perl

okwudili onyejiaku

Overview

In Perl, the reverse() function is used to reverse a string.

Syntax

scalar reverse(string)

Parameters

This function takes the parameter, string, which represents the string we want to reverse.

Return Value

It returns a string in the reverse order of the values of string, passed as a parameter to the reverse() function.

Example

# create strings
@str1 = "osserpdE";
@str2 = "si";
@str3 = "!tseb eht";

# reverse strings
@r1 = scalar reverse @str1;
@r2 = scalar reverse @str2;
@r3 = scalar reverse @str3;

# print reversed strings.
print "@r1\n";
print "@r2\n";
print "@r3\n";
Reverse a String in Perl

Explanation

  • Lines 2–4: We create the strings @str1, @str2, and @str3.
  • Lines 7–9: We use the reverse() method to reverse the strings, and save the results.
  • Lines 12–14: We print the output to the console.

RELATED TAGS

communitycreator
perl
string
RELATED COURSES

View all Courses

Keep Exploring