SPUG: sorting hierarchical section numbers

John W. Krahn krahnj at telus.net
Thu Aug 10 23:59:07 PDT 2006


Michael R. Wolf wrote:
> I want to sort strings that represent outline numbers.  
> 
> 1
> 1.1
> 1.2
> 1.3
> 1.3.1
> 1.3.2
> 1.3.2.1
> 1.2
> 
> I can't find a module.  Could you point me in the correct direction so that
> I can read the fine manual?  I can't seem to find the right search term;
> these are too general 'hierarchy', 'outline', 'number', 'sort'.

$ perl -le'
my @numbers = qw(
    1
    1.1
    1.2
    1.3
    1.3.1
    1.3.2
    1.3.2.1
    1.2
    );
print for
    map $_->[ 0 ],
    sort { $a->[ 1 ] cmp $b->[ 1 ] }
    map [ $_, pack q[C*], split /\./ ],
    @numbers;
'
1
1.1
1.2
1.2
1.3
1.3.1
1.3.2
1.3.2.1


This should work as long as each individual number does not exceed 255, for
larger numbers use 'n*' and for really large numbers use 'N*' for the pack format.


John
-- 
use Perl;
program
fulfillment


More information about the spug-list mailing list