SPUG: sorting hierarchical section numbers

DeRykus, Charles E charles.e.derykus at boeing.com
Fri Aug 11 11:52:21 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'.

JWK>> $ perl -le'
JWK>> my @numbers = qw(
JWK>>    1
JWK>>    1.1
JWK>>    1.2
JWK>>    1.3
JWK>>    1.3.1
JWK>>   1.3.2
JWK>>    1.3.2.1
JWK>>    1.2
JWK>>    );
JWK>>print for
JWK>>    map $_->[ 0 ],
JWK>>    sort { $a->[ 1 ] cmp $b->[ 1 ] }
JWK>>    map [ $_, pack q[C*], split /\./ ],
JWK>>    @numbers;
JWK>> ...
JWK>>This should work as long as each individual number does not exceed
255, for 
JWK>>larger numbers use 'n*' and for really large numbers use 'N*' for
the pack format.

CPAN's Sort::Fields is another possibility although probably not as
efficient: 


  use Sort::Fields;

  my @sorted = fieldsort '\.', [1..99], @numbers;


-- 
Charles DeRykus


More information about the spug-list mailing list