To sort an array in Perl, you can use the sort function.
In this example,
@numbers
with values 5, 2, 8, 1, 6.sort
function to sort the array in ascending order.@numbers
to the console.@numbers = (5, 2, 8, 1, 6);
sort @numbers;
print "Sorted array in ascending order: @numbers\n";
Sorted array in ascending order: 1 2 5 6 8
In this example,
@numbers
with values 5, 2, 8, 1, 6.sort
function with a custom comparison function that sorts in descending order.@numbers
to the console.@numbers = (5, 2, 8, 1, 6);
sub desc_sort { $b <=> $a }
@sorted = sort desc_sort @numbers;
print "Sorted array in descending order: @sorted\n";
Sorted array in descending order: 8 6 5 2 1
In this tutorial, we learned How to Sort an Array in Perl language with well detailed examples.