For any mask,
use strict; use warnings; my @ips = qw( 1.1.1.1 1.1.1.2 1.1.1.127 1.1.1.128 1.1.1.129 10.1.2.5 10.1.2.6 10.1.2.10 ); my $mask = 25; sub pack_ip4 { return pack 'C4', split /\./, $_ for @_ ? $_[0] : $_} sub unpack_ip4 { return join '.', unpack 'C4', $_ for @_ ? $_[0] : $_} sub sort_ip4 { map unpack_ip4, sort map pack_ip4, @_ } my $packed_mask = pack('B32', ('1'x$mask) . ('0'x(32-$mask))); my %by_net; foreach my $ip (@ips) { my $net = unpack_ip4(pack_ip4($ip) & $packed_mask); push @{$by_net{$net}}, $ip; } foreach my $net (sort_ip4(keys(%by_net))) { print("Network $net/$mask:\n"); foreach my $ip (sort_ip4(@{$by_net{$net}})) { print(" $ip\n"); } print("\n"); }
Network 1.1.1.0/25: 1.1.1.1 1.1.1.2 1.1.1.127 Network 1.1.1.128/25: 1.1.1.128 1.1.1.129 Network 10.1.2.0/25: 10.1.2.5 10.1.2.6 10.1.2.10

In reply to Re: Collapsing IP addresses, an approach? by ikegami
in thread Collapsing IP addresses, an approach? by symgryph

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.