A version without eval:

# Supports ranges in any number of bytes. sub parse_ip_mask { my ($ip_mask) = @_; my @checks; foreach (split(/\./, $ip_mask)) { if (/\[(\d+)-(\d+)\]/) { push(@checks, [ 0+$1, 0+$2 ]); } else { push(@checks, [ 0+$_, 0+$_ ]); } } return \@checks; } sub ip_check { my ($ip, $checks) = @_; my @ip = split(/\./, $ip); my $i; for ($i=0; $i<4; $i++) { return undef if ($ip[$i] < $checks->[$i][0]); return undef if ($ip[$i] > $checks->[$i][1]); } return 1; }

Example usage #1, check if an IP is in range:

my $ip_mask = parse_ip_mask('131.202.1.[3-4]'); foreach (qw( 131.202.1.2 131.202.1.3 131.202.1.4 132.202.1.4 )) { print(ip_check($_, $ip_mask) ? "$_ matches.$/" : "$_ doesn't match.$/" ); } __END__ output ====== 131.202.1.2 doesn't match. 131.202.1.3 matches. 131.202.1.4 matches. 132.202.1.4 doesn't match.

Example usage #2, finding matching IPs in a line:

my $ip_mask = parse_ip_mask('131.202.1.[3-4]'); foreach ( 'Connection established to 131.202.1.2', 'Connection established to 131.202.1.3', 'Connection established to 131.202.1.4', 'Connection established to 132.202.1.4', ) { my ($ip) = /(\d+\.\d+\.\d+\.\d+)/; print("Found matching ip $ip.$/") if (ip_check($ip, $ip_mask)); } __END__ output ====== Found matching ip 131.202.1.3. Found matching ip 131.202.1.4.

In reply to Re^2: converting user friendly regex to perl friendly by ikegami
in thread converting user friendly regex to perl friendly by Random_Walk

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.