Yes, using a regular expression is "much more efficient", but yours is in some cases, as you point out,
incorrect. And using
Net::IP::Match::Regexp you can still do more than
sixty seven thousand comparisons per second (on my old and rusty laptop, anyway) if the regexp is initialized once only. So what do you want:
- Superfast and possibly incorrect, or
- Fast and correct?
$ cat 791149.pl
use strict;
use warnings;
use Net::IP::Match::Regexp qw( create_iprange_regexp match_ip );
use Benchmark qw / cmpthese /;
my $regexp_init_once =
create_iprange_regexp( qw( 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 )
+ );
sub netip {
my $regexp =
create_iprange_regexp( qw( 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16
+ ) );
return ( match_ip( $_[0], $regexp ) );
}
sub netip_init_once {
return match_ip( $_[0], $regexp_init_once );
}
sub regexp {
return $_[0] =~ /^(10\.\d+|172\.(1[6-9]|2\d|3[0-1])|192\.168)(\.\d+)
+{2}$/;
}
cmpthese(
-1,
{
'netip' => sub { netip('1.2.3.4') },
'netip_init_once' => sub { netip_init_once('1.2.3.4') },
'regexp' => sub { regexp('1.2.3.4') },
}
);
__END__
$ perl 791149.pl
Rate netip netip_init_once reg
+exp
netip 2438/s -- -96% -1
+00%
netip_init_once 67622/s 2674% -- -
+95%
regexp 1390157/s 56918% 1956%
+ --
--
No matter how great and destructive your problems may seem now, remember, you've probably only seen the tip of them. [1]
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.