Perl | sort() Function

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
@array1 = ("a", "d", "h", "e", "b");
  
print "Original Array: @array1\n";
print ("Sorted Array: ", sort(@array1));

chevron_right


Output:



Original Array: a d h e b
Sorted Array: abdeh

 
Example 2: Use of Block to sort

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
use warnings;
use strict;
  
# Use of Block to sort 
my @numeric = sort { $a <=> $b } (2, 11, 54, 6, 35, 87);
  
print "@numeric\n";

chevron_right


Output:

2 6 11 35 54 87

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

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl -w
use warnings;
use strict;
  
# Calling subroutine to sort numerical array
my @numerical = sort compare_sort (2, 11, 54, 6, 35, 87);
print "@numerical\n";
   
# function to compare two numbers
sub compare_sort
{
   if($a < $b)
   {
      return -1;
   }
   elsif($a == $b)
   {
      return 0;
   }
   else
   {
      return 1;                       
   }
}

chevron_right


Output:

2 6 11 35 54 87


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.