http://www.perlmonks.org?node_id=742470

slatibart has asked for the wisdom of the Perl Monks concerning the following question:

Hi, i have a list of top level domains which also have sub tlds. Normal sort produces me a list like that
.com.fj .com.sb .com.nf .com.co .com.mv .coop
but this would be the appreciated sorting
.com.co .com.fj .com.sb .com.mv .com.nf .com.sb .coop
First, the toplevel, then the sub tld. My ideas was to start with this code :
@list= sort { my ($sub1,$tld1)=split /\./,$a; my ($sub2,$tld2)= spli +t /\./,$b; $tld1 cmp $tld2 } @list;
But didn't worked as expected. Where is my code wrong ? Thanks

Replies are listed 'Best First'.
Re: Custom "sort" routine
by kyle (Abbot) on Feb 09, 2009 at 16:06 UTC

    You don't account for $subX at all.

    my @list = qw( .coop .com.co .com.mv .com.fj .com.sb .com.nf ); @list= sort { my (undef,$sub1,$tld1)=split /\./,$a; my (undef,$sub2,$tld2)= split /\./,$b; warn "[$sub1].[$tld1] cmp [$sub2].[$tld2]\n"; $sub1 cmp $sub2 || $tld1 cmp $tld2 } @list; print "$_\n" for @list; __END__ .com.co .com.fj .com.mv .com.nf .com.sb .coop

    Update: Fixed a couple of problems after reading the comment from moritz.

Re: Custom "sort" routine
by moritz (Cardinal) on Feb 09, 2009 at 16:06 UTC
    First of all you don't use $sub1 and $sub2 in your code. Second point is that if you split on a dot, the first item of the array will be empty, $tld1 will be just com (as pointed out by ambrus++ in the CB).
Re: Custom "sort" routine
by CountZero (Bishop) on Feb 09, 2009 at 16:50 UTC
    And of course if you have a large number of items to sort, this is a prime example where a Schwartzian Transform or an Orcish Maneuver could come in very handy. A nice overview of various sort strategies can be found in Resorting to Sorting and The sort function.

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Custom "sort" routine
by revdiablo (Prior) on Feb 09, 2009 at 17:03 UTC

    Are you sure you even need a custom sort? I don't get what you listed when I use the standard sort. I get the following:

    .com.co .com.fj .com.mv .com.nf .com.sb .coop

    Which is exactly what you said you wanted. Am I missing something in your example?

    For reference, here is my code:

    my @items = qw( .com.fj .com.sb .com.nf .com.co .com.mv .coop ); for (sort @items) { print "$_\n"; }
Re: Custom "sort" routine
by ww (Archbishop) on Feb 09, 2009 at 19:08 UTC
    ... and why does ".com.sb" appear twice in the "appreciated sorting?"