Perl | sort() Function
Last Updated :
17 Mar, 2023
sort() function in Perl is used to sort a list with or without the use of method of sorting. This method can be specified by the user in the form of subroutines or blocks. If a subroutine or block is not specified then it will follow the default method of sorting.
Syntax: sort List sort block, List sort Subroutine, List Returns: sorted list as per user’s requirement
Example 1:
Perl
#!/usr/bin/perl
@array1 = ("a", "d", "h", "e", "b");
print "Original Array: @array1 \n";
print ("Sorted Array: ", sort ( @array1 ));
|
Output:
Original Array: a d h e b
Sorted Array: abdeh
Example 2: Use of Block to sort
Perl
#!/usr/bin/perl -w
use warnings;
use strict;
my @numeric = sort { $a <=> $b } (2, 11, 54, 6, 35, 87);
print " @numeric \n";
|
In the above code, block is used to sort because sort() function uses characters to sort the strings, but in numerical context, it is not possible to follow the same. Hence, block is used to ease the sort.
Example 3: Use of Subroutine to sort
Perl
#!/usr/bin/perl -w
use warnings;
use strict;
my @numerical = sort compare_sort (2, 11, 54, 6, 35, 87);
print " @numerical \n";
sub compare_sort
{
if ( $a < $b )
{
return -1;
}
elsif ( $a == $b )
{
return 0;
}
else
{
return 1;
}
}
|
Example – 4 : Mixed case
Here we will see how the sort function works if we have an array of strings with mixed case (upper or lower) for the first character of each string.
Perl
#!/usr/bin/perl
@st_arr = ( "geeks" , "For" , "Geeks" , "Is" , "best" , "for" , "Coding" );
@lst = sort ( @st_arr );
print ( "@lst" );
|
Output
Coding For Geeks Is best for geeks
Here we can see that the sort function first sorted the strings which has upper case letters at the beginning in ascending order (A-Z) and then it sorted the rest which has lower case letters at the beginning in ascending order (a-z). This happened due to the fact that the ASCII values of upper case letters is less than that of lowercase letters.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...