Skip to content
Related Articles

Related Articles

Improve Article

Perl | sort() Function

  • Last Updated : 07 May, 2019

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:




#!/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




#!/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";
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




#!/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;                       
   }
}
Output:
2 6 11 35 54 87



My Personal Notes arrow_drop_up
Recommended Articles
Page :