Beefy Boxes and Bandwidth Generously Provided by pair Networks Joe
Just another Perl shrine
 
PerlMonks  

Ipsort

by bent (Scribe)
on Dec 07, 2000 at 04:30 UTC ( #45397=snippet: print w/ replies, xml ) Need Help??

Description: Sort IP addresses. This is just a straight forward sort, but it's a task that pops up often (web log analysis etc.)
sub ipsort {
    return map {$_->[0]} sort {$a->[1] cmp $b->[1]} map {[$_, split]} 
+@_;
}
Comment on Ipsort
Download Code
Re: Ipsort
by Fastolfe (Vicar) on Dec 07, 2000 at 05:03 UTC
    Won't this put 1.1.1.50 between 1.1.1.5 and 1.1.1.6?
Re: Ipsort
by dws (Chancellor) on Dec 07, 2000 at 05:44 UTC
    This was covered here a while back. Here's one way that uses a cache to cut down on the number of packs required.
    my %cache = ();
    my @sorted = sort {
            $cache{$a} ||= pack('C4' => $a =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/);
            $cache{$b} ||= pack('C4' => $b =~ /(\d+)\.(\d+)\.(\d+)\.(\d+)/);
            $cache{$a} cmp $cache{$b};
    } @unsorted;
    
Re: Ipsort
by runrig (Abbot) on Dec 08, 2000 at 06:35 UTC
    my @ips = qw(100.100.100.100 1.1.1.1); my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [ $_, sprintf("%03d" x 4, split(/\./, $_)) ] } @ips; # OR my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, pack("C*", split(/\./, $_))] } @ips;
      #or my @sorted = map {join".",unpack'C*',$_} sort map{pack"C*",split/\./} +@ips; #or, in v5.6.0 my @sorted = map {sprintf"%vd",$_} sort map{eval "v$_"} @ips;

Back to Snippets Section

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (7)
As of 2014-04-19 18:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (483 votes), past polls