Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot


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(; 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 between and
Log In?

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

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (1)
As of 2018-03-21 04:10 GMT
Find Nodes?
    Voting Booth?
    When I think of a mole I think of:

    Results (263 votes). Check out past polls.