This is code I wrote to test an idea to solve the problem Dominus posted in Challenge Problem: Merging Network Addresses. The benchmark shows an order of magnitude speed increase over using Net::CIDR, as I had originally suggested. And it's an unusual (ab-)use of the regex engine. Enjoy.

(Yes, I'm writing a column about my findings. {grin})

#!/usr/bin/perl -w use strict; $|++; use Socket qw(inet_aton inet_ntoa); sub cidr2bits { my $cidr = shift; my ($addr, $maskbits) = $cidr =~ /^([\d.]+)\/(\d+)$/ or die "bad format for cidr: $cidr"; substr(unpack("B*", inet_aton($addr)), 0, $maskbits); } sub bits2cidr { my $bits = shift; inet_ntoa(pack "B*", substr("${bits}00000000000000000000000000000000", 0, 32)) . "/" . length($bits); } sub mergecidr { local $_ = join "", sort map { cidr2bits($_)."\n" } @_; 1 while s/^(\d+)0\n\1[1]\n/$1\n/m or s/^(\d+)\n\1\d+\n/$1\n/m; map bits2cidr($_), split /\n/; } my @first = qw( 209.152.214.112/30 209.152.214.116/31 209.152.214.118/31 ); my @second = qw( 209.152.214.112/30 209.152.214.116/32 209.152.214.118/31 ); my @third = qw( 209.152.214.112/31 209.152.214.116/31 209.152.214.118/31 ); if (1) { print join "----\n", map join("", "from:\n", map(" $_\n", @$_), "to:\n", map(" $_\n", mergecidr(@$_))), \@first, \@second, \@third; }

In reply to Merge CIDRs by merlyn

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.