Since the OP was using NetAddr::IP, what follows is a version that uses that module.

I used the same approach as in my earlier post. The main difference is that sorting is trickier because we are working with the string form. A plain (lexical) sort won't do because 20.0.0.0 would sort after 198.162.0.0.

use strict; use warnings; use NetAddr::IP qw( ); my $subnet_mask = 29; my @ip_xfers = ( [ '10.0.0.1', 555555 ], [ '10.2.1.6', 444444 ], [ '10.6.2.8', 333333 ], [ '10.2.1.2', 222222 ], ); my %subnet_xfers; foreach (@ip_xfers) { my ($ip, $xfer) = @$_; my $subnet = NetAddr::IP->new($ip, $subnet_mask)->network(); my $subnet_ip = $subnet->addr(); # Save NetAddr::IP for sorting. $subnet_xfers{$subnet_ip} ||= [ $subnet, 0 ]; $subnet_xfers{$subnet_ip}[1] += $xfer; } my @sorted_keys = sort { $subnet_xfers{$a}[0]->aton() cmp $subnet_xfers{$b}[0]->aton() } keys %subnet_xfers; foreach (@sorted_keys) { my ($subnet, $xfer) = @{$subnet_xfers{$_}}; print("$subnet: $xfer\n"); }
10.0.0.0/29: 555555 10.2.1.0/29: 666666 10.6.2.8/29: 333333

Update: I originally didn't sort the output due to the extra complexity.


In reply to Re^2: Sorting IP Subnets together by ikegami
in thread Sorting IP Subnets together by strat.minger

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.