Perl reverse Function
The reverse function in scalar context concatenates the elements of a list and returns a string value with all characters in the opposite order.
You can use the Perl reverse function in either a scalar or list context. 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.
In a list context, it reverses the order of an array.
In a scalar context it is used either to reverse a string value with the characters in an opposite order or to reverse an array into a string.
The syntax forms of the Perl reverse function are as follows:
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 $_
You can use the Perl reverse function to reverse the words of a sentence.
Here’s an example:
Finally, the content of the $sentence variable will be printed.
By definition a word, phrase, or sentence is palindrome if reads the same backward or forward. The following example shows you how you can check up if the content of a string variable is palindrome, by using the reverse function and the regex s/// substitution operator.
See the code:
- to make the comparison case insensitive, $str is converted in lowercase and then is assigned to $_
- the s/// regex substitution operator is used to get rid off some punctuation characters as space, dot, comma, dash, colon, semicolon, question mark and exclamation mark. The dot and dash characters need to be escaped because they are metacharacters and have special meaning to regex engine. These characters are enclosed in square brackets (we say that we defined a character class) to specify that we want to match any of them. The + metacharacter specifies that any character from the class can be repeated more than once. The /g modifier is used to process all regex matches in a string. The substitution operator acts against $_.
- The reverse function test if the value stored in $_ is a palindrome (the ternary operator is used to test and print the appropriate message.
The output: