SPUG: sorting hierarchical section numbers

Aaron West tallpeak at hotmail.com
Fri Aug 11 16:09:53 PDT 2006


Not quite; the sort is not numeric, and not right-justified, and the
field-offset array-ref must be 0-based.

$ perl -le 'use Sort::Fields;
 my @numbers = qw(3 5 12 1 13.1 12.2 1.3 1.2 1.4 1.1a 1.1 1.1z 1.1y) ; 
 my @sorted = fieldsort "\.", [0..99], @numbers;
 print for @sorted;
'

1
1.1
1.1a
1.1y
1.1z
1.2
1.3
1.4
12
12.2
13.1
3
5  

-----Original Message-----
From: spug-list-bounces+tallpeak=hotmail.com at pm.org
[mailto:spug-list-bounces+tallpeak=hotmail.com at pm.org] On Behalf Of DeRykus,
Charles E
Sent: Friday, August 11, 2006 11:52 AM
To: SPUG
Subject: Re: SPUG: sorting hierarchical section numbers

 

> 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
_____________________________________________________________
Seattle Perl Users Group Mailing List  
     POST TO: spug-list at pm.org
SUBSCRIPTION: http://mail.pm.org/mailman/listinfo/spug-list
    MEETINGS: 3rd Tuesdays
    WEB PAGE: http://seattleperl.org/

-- 
No virus found in this incoming message.
Checked by AVG Free Edition.
Version: 7.1.405 / Virus Database: 268.10.9/417 - Release Date: 8/11/2006
 

-- 
No virus found in this outgoing message.
Checked by AVG Free Edition.
Version: 7.1.405 / Virus Database: 268.10.9/417 - Release Date: 8/11/2006
 



More information about the spug-list mailing list