perl function sort

www.i‮.aeditfig‬com

The sort function in Perl sorts a list of values and returns the sorted list. The sort order can be customized using a subroutine that compares the values being sorted. Here's an example:

my @numbers = (5, 3, 1, 4, 2);

# Sort the numbers in ascending order
my @sorted_numbers = sort {$a <=> $b} @numbers;

print "Ascending order: @sorted_numbers\n";

# Sort the numbers in descending order
@sorted_numbers = sort {$b <=> $a} @numbers;

print "Descending order: @sorted_numbers\n";

# Sort a list of strings
my @words = ("apple", "banana", "cherry", "date");

# Sort the words in alphabetical order
my @sorted_words = sort @words;

print "Alphabetical order: @sorted_words\n";

# Sort the words in reverse alphabetical order
@sorted_words = sort {$b cmp $a} @words;

print "Reverse alphabetical order: @sorted_words\n";

In this example, we start by defining an array of numbers (@numbers). We then use sort to sort the numbers in ascending order using the comparison operator <=>. The comparison operator compares two numbers and returns -1 if the first number is less than the second, 0 if they are equal, or 1 if the first number is greater than the second. By using <=> in the comparison subroutine for sort, we are telling it to sort the numbers in ascending order.

We then sort the numbers in descending order by reversing the order of the comparison operands (i.e., using $b <=> $a instead of $a <=> $b).

Next, we define an array of strings (@words) and use sort to sort them in alphabetical order using the default string comparison operator cmp. We then sort the words in reverse alphabetical order by reversing the order of the comparison operands (i.e., using $b cmp $a instead of $a cmp $b).

Note that the sort function sorts the elements of the original array in place, so if you want to preserve the original order of the array, you should make a copy of it before sorting. For example:

my @numbers = (5, 3, 1, 4, 2);
my @sorted_numbers = sort {$a <=> $b} @numbers;

# Make a copy of @numbers before sorting
my @original_numbers = @numbers;

print "Sorted numbers: @sorted_numbers\n";
print "Original numbers: @original_numbers\n";

This will output:

Sorted numbers: 1 2 3 4 5
Original numbers: 5 3 1 4 2