To iterate over an array in Perl in reverse order, you can use the reverse
function or a for
loop starting from the last index to the first index.
In this example,
@numbers
with some values.reverse
function to reverse the order of elements in the array.for
loop to iterate over each element of the reversed array.@numbers = (1, 2, 3, 4, 5);
@reversed_numbers = reverse @numbers;
foreach $number (@reversed_numbers) {
print "$number\n";
}
5 4 3 2 1
In this example,
@fruits
with some values.for
loop starting from the last index to iterate over each element of the array in reverse order.@fruits = ("apple", "banana", "cherry");
for ($i = $#fruits; $i >= 0; $i--) {
print "$fruits[$i]\n";
}
cherry banana apple
In this tutorial, we learned How to Iterate Over an Array in Reverse Order in Perl language with well detailed examples.