You could try NetAddr::IP:

use strict; use warnings; use Test::More; use NetAddr::IP; my @routes = ( [ qw(192.168.0.0/24 192.168.0.1) ], [ qw(10.10.10.0/24 10.10.10.1) ], [ qw(12.162.8.11/28 default) ], ); is( calc_route( "192.168.0.88" ), "192.168.0.1", "first route" ); is( calc_route( "192.168.1.88" ), "default", "close to first rout +e but default" ); is( calc_route( "10.10.10.12" ), "10.10.10.1", "second route (examp +le IP)" ); is( calc_route( "12.162.8.3" ), "default", "explicit default" ) +; is( calc_route( "1.2.3.4" ), "default", "else: default" ); done_testing; sub calc_route { my $ip = NetAddr::IP->new( shift ); for my $test_subnet ( @routes ) { if ( $ip->within( NetAddr::IP->new( $test_subnet->[0] ) ) ) { return $test_subnet->[1]; } } return 'default'; }

Result:

ok 1 - first route ok 2 - close to first route but default ok 3 - second route (example IP) ok 4 - explicit default ok 5 - else: default 1..5

Use hashes and pre-computed objects for better performance (left as an exercise ;-).


In reply to Re: Determine which route to take by Perlbotics
in thread Determine which route to take by mhearse

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.