Perl reverse Function
The reverse function in scalar context concatenates the elements of a list in a string and returns the string with all the characters in an opposite order; in a list context, it returns the list in the reversed order.
You can use the reverse function either in scalar or list context.
The syntax forms of the Perl reverse function are as follows:
If you want to keep the result returned by the function, you need to assign it back to a variable.
As you can see, there are at least 4 syntax forms for this function.
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 $_
See the following examples for an exemplification of the syntax forms of Perl reverse function.
You can use both the sort and Perl reverse function to sort an array in a descending alphabetical order. By default the sort function compares the ASCII values of the array elements, so if you have an array of numbers you need to use the <=> operator explicitly to get a correct ordered list.
Here's an example:
The following example shows you how to invert a hash, by swapping the keys with the values. However, at first ensure yourself that your hash has unique values, otherwise the resulting hash will have fewer elements that the initial one.
Here's an example:
The foreach statement is used to print the elements of the hash. The keys function returns the keys of the hash unordered, so if you want to print the hash keys in an ascending or descending order, you need to use the sort function.
Because after inverting the hash the keys are numbers, the <=> operator is used. In our example the inverted hash is printed with the keys in an ascending order.
If you want a descending order you need to swap $a with $b in the sort function: $b<=>$a. If you want to sort the hash keys alphabetically, you need to use instead the <=> operator, the cmp operator.
You can use the Perl reverse function to reverse the words of a sentence.
Here's an example:
You can write a shorthand version of this code using of $_ special variable:
You can build a matrix with three rows and three columns and populate a bi-dimensional array with the matrix elements.
You can emulate a bi-dimensional array from a usual array that has as elements references to other arrays. The Perl reverse function will be used to reverse the order of the columns.
See the code:
The output is as follows:
6 5 4
9 8 7