Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
The stupid question is the question not asked
 
PerlMonks  

Re: Sorting path like strings

by athomason (Curate)
on Jan 05, 2006 at 08:52 UTC ( #521142=note: print w/ replies, xml ) Need Help??


in reply to Sorting path like strings

Your sort operator needs to impose a lexicographic ordering on the lists defined by your "paths", as in this example:

#!/usr/bin/perl use strict; use warnings; # parse the paths into lists my @data; while ( <DATA> ) { chomp; push @data, [ split m:/:, $_ ]; } sub compare_lists_lexicographically { # make copies of the input lists my @left = @$a; my @right = @$b; # chew threw the lists until # a) we discover they're different lengths, or # b) the elements are different, or # c) neither while ( 1 ) { if ( !@left && !@right ) { # ran out at the same time: they're equal return 0; } elsif ( !@left ) { # left is shorter than right: left is first return -1; } elsif ( !@right ) { # right is shorter than left: right is first return 1; } else { # check the next element from each list my ( $l, $r ) = ( shift @left, shift @right ); # NB: use < if fields are numeric, lt otherwise if ( $l < $r ) { # next element of left comes first return -1; } elsif ( $r < $l ) { # next element of right comes first return 1; } # else equal, keep checking } } } # display the output printf "%s\n", join '/', @$_ for sort compare_lists_lexicographically +@data; __DATA__ 0/1/2/3 0 0/4/5/6 0/4 0/1 0/1/2 0/4/5 0/10/111/145 0/10/111 0/10
HTH,
--athomason


Comment on Re: Sorting path like strings
Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://521142]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (7)
As of 2014-04-21 03:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (490 votes), past polls