Arijit Arijit - 5 months ago 13
Perl Question

How to sort an alphanumeric array in perl?

I have an alphanumeric array called

my @array1= (gee0,gee1,gee7,gee10,gee12,gee20,gee24,gee15,gee8,gee47);


How can I sort the above alphanumeric array?

Answer

An alternative to the Schwartzian Transform is to create a new array of the transformed values that you want to sort by, sort that array's indices, and use the sorted indices to reorder the original data as an array slice.

It loks like this

use strict;
use warnings;

my @array   = qw/ gee0 gee1 gee7 gee10 gee12 gee20 gee24 gee15 gee8 gee47 /;
my @values  = map /(\d+)/, @array;
my @indices = sort { $values[$a] <=> $values[$b] } 0 .. $#values;

print "$array[$_]\n" for @indices;

output

gee0
gee1
gee7
gee8
gee10
gee12
gee15
gee20
gee24
gee47
Comments