reverse Function in Perl
What is reverse Function in Perl?
Explanation
The reverse() is used to flip a string or list.
Syntax:
reverse(list)
scalar reverse(string)
In the above syntax reverse function takes a "string" as well as a "list" as argument.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
@arr = (1,2,3,4,5,6);
print "Reversed List Structure", reverse(@arr), "n";
$str = "Hiox India";
print "Reversed String Value ", scalar reverse("$str"), "n";
Result :
Reversed list structure:654321
Reversed String Value:aidnI xoiH
In the above example first an array elements are reversed, then the string "Hiox India" is reversed.
Example :
#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
%name = ('Tom', 26, 'Peter', 51, 'Jones', 23);
%inverted = reverse %name;
while (($key, $value) = each(%name))
{
print $key.", ".$value."<br/>";
}
Result :
Jones, 23
Peter, 51
Tom, 26
In the above reverse Function example, a hash "%name" is reversed and stored in another hash "%inverted", then the values are printed using a loop.