Thursday, December 09, 2010

Alphanumeric sort

Sometimes I have lists that look like:

someThing1
someThing2
..
someThing15

...and I want to sort them numerically, but that doesn't happen because the string part of the scalar makes the compiler think it needs to sort strings which make the items line up like:

someThing1
someThing102093848984
someThing111
someThing2
someThing3

To resolve this, pass the list to sort, which you then pass to substr the second parameter of which you pass to a sub to get the length of the alpha portion of the element, thus giving you the alpha substring within each item to be compared.


my @unsorted = qw(item10 foobar92 item1 doe2 a6 item7);

my @sorted = sort {substr($a, &lengthOfAlpha($a)) <=> substr($b, &lengthOfAlpha($b))} @unsorted;

foreach my $foo(@sorted)
{
  print "$foo\n";
}

sub lengthOfAlpha
{
  my ($input) = @_;
  my ($alpha) = $input =~ /(\D{1,})/;
  my $length = length($alpha);
  print "length of alpha is $length\n";
  return $length;
}

No comments: