Perl reverse Function
This short Perl reverse Tutorial will show you how to use this function in your scripts, 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.
The syntax forms of the Perl reverse function are as follows:
@reversedArray = reverse @array;
$str = reverse @array;
$newStr = reverse $str;
$str = reverse;
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 example for an exemplification of all these syntax forms below.
#!/usr/local/bin/perl
use strict;
use warnings;
my @array = qw(one two three four);
# list context
my @reversedArray = reverse @array;
print "@reversedArray\n";
# it displays: four three two one
# scalar contexts
my $str = reverse @array;
print "$str\n";
# it displays: ruofeerhtowteno
$str = reverse $str;
print "$str\n";
# it displays: onetwothreefour
# the next two examples use reverse with $_
print scalar reverse, " " foreach (@array);
# it displays: eno owt eerht ruof
print "\n";
$_ = "1234";
$_ = reverse;
print;
# it displays: 4321
print "\n";
| Sort an array in a reversed order |
You can use both the
sort and
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:
#!/usr/local/bin/perl
use strict;
use warnings;
my @array = qw(13 21 15 175 1 );
@array = reverse sort ({$a <=> $b} @array);
print "@array\n";
# it displays: 175 21 15 13 1
You can get the same output without using the Perl
reverse function by swapping the
$a and
$b special variables:
@array = sort ({$b <=> $a} @array);
If your array contains strings as elements, you can omit the
cmp operator and the above line of code will look like this:
@array = reverse sort @array;
| Using reverse to invert a hash |
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:
#!/usr/local/bin/perl
use strict;
use warnings;
my %hash = (one => 1, two => 2,
three => 3, four => 4);
%hash = reverse %hash;
foreach my $key (sort {$a <=> $b} keys %hash) {
print "$key=>$hash{$key}, ";
}
print "\n";
# it displays: 1=>one, 2=>two, 3=>three, 4=>four
The Perl
reverse function inverts the
%hash by swapping the values with the keys. The
foreach statement prints 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.
| Get a sentence with the words in an inverted order |
You can use the Perl
reverse function to reverse the words of a sentence.
Here’s an example:
#!/usr/local/bin/perl
use strict;
use warnings;
my $sentence = 'This is about the Perl reverse function';
my @words = split /\s+/, $sentence;
@words = reverse @words;
$sentence = join ' ', @words;
print "$sentence\n";
#it displays: function reverse Perl the about is This
The
split function will return an array from the
$sentence string and the array will be inverted by the Perl
reverse function. Next the
join function will concatenate the elements of the array into the
$sentence variable, using the space delimiter. Finally, the content of the
$sentence variable will be printed.
You can write a shorthand version of this code using of $_ special variable:
#!/usr/local/bin/perl
use strict;
use warnings;
$_ = 'This is about the Perl reverse function';
print join(' ', reverse (split)), "\n";
#it displays: function reverse Perl the about is This
Here the
split function is used without any argument, therefore
$_ will be used as expression and whitespace as separator.
| Reverse the rows of a matrix hold in an array |
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 rows.
See the code:
#!/usr/local/bin/perl
use strict;
use warnings;
my @matrix = ( [1, 2, 3],
[4, 5, 6],
[7, 8, 9]
);
foreach my $i (@matrix) {
foreach my $j (reverse @$i) {
print "$j ";
}
print "\n";
}
To traverse the bi-dimensional array, a nested
foreach is used. The
@$i is used to dereference the references of the
@matrix array.
The output is as follows:
An alternative to populate the
@matrix array is as follows:
my @rows1 = (1, 2, 3);
my @rows2 = (4, 5, 6);
my @rows3 = (7, 8, 9);
my @matrix = (\@rows1, \@rows2, \@rows3);
Please click
here to download the Perl
reverse script with all the above examples included.
Table of Contents:
A Perl Script
Install Perl
Running Perl
Perl Data Types
Perl Variables
Perl Operators
Perl Lists
Perl Arrays
Array Size
Array Length
Perl Hashes
Perl Statements
Perl if
Perl unless
Perl switch
Perl while
Perl do-while
Perl until
Perl do-until
Perl for
Perl foreach
Built-in Perl Functions
Functions by Category
String Functions
Regular Expressions and Pattern Matching
List Functions
Array Functions
Hash Functions
Miscellaneous Functions
Functions in alphabetical order
chomp
chop
chr
crypt
defined
delete
each
exists
grep
hex
index
join
keys
lc
lcfirst
length
map
oct
ord
pack
pop
push
q
qq
qw
reverse (more)
rindex
scalar
shift
sort
splice
split
sprintf
substr
tr
uc
ucfirst
undef
unpack
unshift
values
return from Perl reverse function to Perl Basics
Would you like to create your own website like this one?
Hit the Alarm Clock!