use Socket; my $ip = '127.0.0.1'; print unpack('N', inet_aton($ip)),"\n"; __END__ 2130706433
An equivalent would be
my $ip = '127.0.0.1'; print unpack('N', pack 'C*', split /\./, $ip),"\n"; __END__ 2130706433
Now, for sorting them, you don't want to split / pack / unpack them for every comparison of two items during the sort. So make an list of anonymous arrays holding each [ $numeric, $ip ], sort them via the first element and pull out the second from the sorted list:
use Socket; chomp(my @ips = <DATA>); my @sorted = map { $_->[1] } # pull out second element sort {$a->[0] <=> $b->[0]} # sort list of arrays by first +element map { [ # construct an anonymous array +with a unpack('N',inet_aton($_)), # transformed IP address $_ # and IP address ] } @ips; # your input list print "$_\n" for @sorted; __DATA__ 192.168.10.15 10.24.13.88 172.16.254.13 10.24.13.89 89.67.128.254
Result:
10.24.13.88 10.24.13.89 89.67.128.254 172.16.254.13 192.168.10.15
Sorting IPs might well be a FAQ...
<update>
Wrapped inet_aton in unpack, s/chop/chomp/. Thanks, ikegami.
</update>
--shmem
_($_=" "x(1<<5)."?\n".q·/)Oo. G°\ /
/\_¯/(q /
---------------------------- \__(m.====·.(_("always off the crowd"))."·
");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
In reply to Re: How to sort IP addresses
by shmem
in thread How to sort IP addresses
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |