Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
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]} 
+@_;
}
Replies are listed 'Best First'.
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;
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?
Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: snippet [id://45397]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (9)
As of 2017-03-28 19:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (340 votes). Check out past polls.