Open In App

Sorting mixed Strings in Perl

Sorting in Perl can be done with the use of a pre-defined function ‘sort’. This function uses a quicksort algorithm to sort the array passed to it.

Syntax: sort @array



Returns: a sorted array

Sorting of an array that contains strings in the mixed form i.e. alphanumeric strings can be done in various ways with the use of sort() function.



Example:

Input :  Key_8, pub_12, pri_4 (array of strings) 
Output :  pri_4 Key_8 pub_12

Sorting of such arrays is done by extracting the numbers from the strings which can be done in two ways:

 
String without a Number: If the array consists of strings in which some of the strings don’t have a number in it, then 0 can be used in place of that number. To check if there is no number in the string, following code is used:

    my @y = sort { (($a =~ /(\d+)/)[0] || 0)  (($b =~ /(\d+)/)[0] || 0) } @x;  




#!/usr/bin/perl
use strict;
use 5.010;
  
# Array with mixed type of strings
my @x = qw(pri_4 Key pubg_12);
  
# Function call with a Regular Expression
my @y = sort { (($a =~ /(\d+)/)[0] || 0) <=> 
               (($b =~ /(\d+)/)[0] || 0) } @x;
   
# Printing the sorted array
print join " ", @y;

Output:
Key pri_4 pubg_12

Sorting using a Subroutine: For better modularization of code we can create separate function or subroutine in Perl and perform the sorting operation with the use of that subroutine. sort() function here takes the subroutine name as the parameter and calls the subroutine which holds the definition for sorting.




#!/usr/bin/perl
use strict;
use 5.010;
  
# Defining an array with strings
my @x = qw(Key_8 pri_4 pubg_12);
  
# Calling sort function to sort 
# array using subroutine
my @y = sort numbersort @x;
  
# Printing the sorted array
print join " ", @y;
  
# Subroutine to sort the array
sub numbersort 
{
    my ( $anum ) = $a =~ /(\d+)/;
    my ( $bnum ) = $b =~ /(\d+)/;
    ( $anum || 0 ) <=> ( $bnum || 0 );
}

Output:
pri_4 Key_8 pubg_12

Article Tags :