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?