Sorting Section Numbers

Here’s a code to sort section numbers in ascending order:


sub sort_sections {
    my ($data) = @_;

    my $sorted = ();
    @$sorted = map { $_->[0] }
        sort {
            my $x=1;
            while (defined $b->[1][$x]) {
                defined $a->[1][$x] or return -1;
                if ($x%2) {
                    ## Strict numeric comparison
                    return 1
                        if $a->[1][$x] > $b->[1][$x];
                    return -1
                        if $a->[1][$x] [1][$x];
                } else {
                    ## Non-numeric comparison
                    return 1
                        if $a->[1][$x] gt $b->[1][$x];
                    return -1
                        if $a->[1][$x] lt $b->[1][$x];
                }
                $x++;
            }
            return defined $a->[1][$x] ? 1 : 0;
        }
        map { [$_, [split(/(d+)/, $_)]] } @$data;

    return $sorted;
}

Here’s a test for it:


$sects = ['1.1', '1.2.2', '1.3', '1.2', '1.3.1'];
print Dumper($sects);

$sorted_sects = sort_sections($sects);

use Data::Dumper;
print Dumper($sorted_sects);

And here’s the output:


$VAR1 = [
          '1.1',
          '1.2.2',
          '1.3',
          '1.2',
          '1.3.1'
        ];
$VAR1 = [
          '1.1',
          '1.2',
          '1.2.2',
          '1.3',
          '1.3.1'
        ];

Found in Perlmonks.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.