![]() |
VOOZH | about |
Syntax: sort @array Returns: a sorted arraySorting 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_12Sorting of such arrays is done by extracting the numbers from the strings which can be done in two ways:
prin_4 Keys_8 pubg_12
For Example- if the array consists "Keys_8_keys" then it's difficult to handle such case, hence for proper filtering of the number from the string, Regular Expressions are used. Note: This method doesn't care if the alphanumeric strings are of different sizes.
usestrict;
use5.010;
# Sample string to extract
# number from
my$str='Key_8_key';
# Regular expression to extract the number
my($number)=$str=~ /(\d+)/;
# Printing the extracted number
print"Number Extracted from Key_8_key is $number\n";
# Defining the array with
# Alphanumeric strings
my@x=qw(pri_4 Key_8_key pubg_12);
# Array before sorting
print"\nArray Before sorting\n";
printjoin" ",sort@x;
# Calling the sort function
# with Regular Expression
my@y=sort{($a=~ /(\d+)/)[0]<=>($b=~ /(\d+)/)[0]}@x;
# Printing the Array after sorting
print"\n\nArray After sorting\n";
printjoin" ",@y;
Number Extracted from Key_8_key is 8 Array Before sorting Key_8_key pri_4 pubg_12 Array After sorting pri_4 Key_8_key pubg_12
my @y = sort { (($a =~ /(\d+)/)[0] || 0) (($b =~ /(\d+)/)[0] || 0) } @x;
Key pri_4 pubg_12
pri_4 Key_8 pubg_12