DEV Community

loading...

Discussion on: Daily Challenge #31 - Count IPv4 Addresses

Collapse
choroba profile image
E. Choroba

Perl, using recursion. Tests included. It throws an exception if the end address precedes the start one.

#!/usr/bin/perl
use warnings;
use strict;

sub _ips_between {
    my ($list1, $list2, $sum) = @_;
    return $sum unless @$list1;

    my ($e1, $e2) = (shift @$list1, shift @$list2);
    die "End before start.\n" if $e2 < $e1 && $sum == 0;

    return _ips_between($list1, $list2, $sum + ($e2 - $e1) * 256 ** @$list1)
}

sub ips_between {
    _ips_between([split /\./, shift],
                 [split /\./, shift],
                 0)
}

use Test::More tests => 6;
use Test::Exception;

is ips_between('10.0.0.0', '10.0.0.50'), 50;
is ips_between('10.0.0.0', '10.0.1.0'), 256;
is ips_between('20.0.0.10', '20.0.1.0'), 246;
is ips_between('0.255.127.12', '1.2.3.4'), 164_856;
is ips_between('1.1.1.1', '1.1.1.1'), 0;
throws_ok { ips_between('1.1.1.1', '1.1.0.1') } qr/End before start/;