Tuesday, July 22, 2008

Sorting alphanumeric strings in Perl

One of my friends had trouble sorting alphanumeric strings in Perl. Strings he had were similar to:
child1
child3
child11
child51
child5
child24

He wanted to sort them based on the numbers that follow after the alphabtic part. So, the order he wanted:

child1
child3
child5
child11
child24
child51

I extracted the numeric part from the alphanumeric string and used it for comparisons
@alphanumeric_sorted = sort { substr($a, 5) <=> substr($b, 5)} @alphanumeric;

1 comment:

  1. One could also add something like the following to keep from having to hard-code the length of the alpha in the second substr parameter:

    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;
    }

    ReplyDelete