IP addresses (v4, that is) are four bytes, separated by dots. A sequence like 123.456.789.12 is no valid IP address, since 456 and 789 overflow a byte, which can be 0..255. You can sort IP addresses easily converting them into numbers. There are several ways to do that. You can e.g use the inet_aton routine form Socket:
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

See Socket, map, sort.

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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.