CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Regular Expressions:
sorting IPs



Apr 5, 2001, 1:34 PM

Post #1 of 4 (2516 views)
sorting IPs Can't Post

OK... call me crazy but I want to sort a list of IPs

Currently I am using this:
@SORTED_IPS = sort keys %{ { map {$_ => 1} @IPS} };
This is how I sorted everything in the past and that works great...

except for IPs, it produces a list like this:

I don't like this. I want IPs with 1 or 2 digits in a set to appear before IPs with 3 digits in that same set like this:

Not sure if I am making any sense but I can't think of a better way to describe it. Imagine if each set within an IP were zero filled to 3 digits, the sort would come out the way I want it.. I don't really know anything about IPs so perhaps my wording is improper.

Any ideas?



Apr 5, 2001, 8:28 PM

Post #2 of 4 (2511 views)
Re: sorting IPs [In reply to] Can't Post

There's really no need for map here:

@SORTED_IPS = sort { $a <=> $b } @ips; 

print join "\n", @SORTED_IPS;

The above prints:


The downside to this is that you'll get a lot of warnings that " isn't numeric". You can avoid this by turning off warnings:

no warnings; 
@SORTED_IPS = sort { $a <=> $b } @ips;
use warnings;

print join "\n", @SORTED_IPS;

Hope this helps!

Enthusiast / Moderator

Apr 6, 2001, 7:46 AM

Post #3 of 4 (2508 views)
Re: sorting IPs [In reply to] Can't Post

The fastest way to sort IP addresses is radix sort (look it up in your neighborhood friendly algorithm book).

Here's a Perl implementation:

use Socket qw( inet_aton inet_ntoa ); 

sub IP_radix_sort {
for (my $i = 3; $i >= 0; $i--) {
my @table;
for (@_) {
push @{ $table[unpack "\@$i C", $_] }, $_;
@_ = map @$_, @table;
return @_;

sub IPsort {
map inet_ntoa($_),
map inet_aton($_),

You call the function @sorted = IPsort @unsorted.

Jeff "japhy" Pinyan -- accomplished hacker, teacher, lecturer, and author

(This post was edited by japhy on Apr 23, 2001, 7:16 AM)


Apr 6, 2001, 9:47 AM

Post #4 of 4 (2506 views)
Re: sorting IPs [In reply to] Can't Post

Thanks Jasmine

that worked. For some reason I don't get warnings about the IP not being numeric. and when I used the "no warnings" it breaks. I think my host is not using warnings. I get a "can't find" error in my logs... anyway all is good.

However, I forgot to mention that the map was there to strip out the duplicates. So now first I strip the duplicates using my original sort/map and then I sort them using your sort. Is there a way to combine these two steps back into one step?

PS. Glad to see you resolved the Netscape/Search issue I emailed about a few weeks back


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives