Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Sorting path like strings

by athomason (Curate)
on Jan 05, 2006 at 08:52 UTC ( [id://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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (4)
As of 2024-03-29 05:27 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found