in reply to I want to be a Perl Jedi
The problem with this code's performance is, each time through the foreach() loop, the regular expression is recompiled. One step better would be to build an alteration out of the array:my @bad_ports = qw(12345 12346 20034 8787 31337 31338 54320 54321); while(<FWLOG>){ foreach my $port (@bad_ports) { if (/\b$port\b/) { print; last; } } }
The /o on the regular expression means "even though there's a variable in there, it wont' change, so compile the regex only once."# I'd separate this out and put it in a configuration section of th +e script my $bad_ports = '12345|12346|20034|8787|31337|31338|54320|54321'; my $found = 0; while(<FWLOG>){ print if (/\b($bad_ports)\b/o); }
In the spirit of "there's more than one way to do it," the last option I'll present is to use a hash. In this method, you do one regular expression match on your logfile line to extract the port (I don't know what your log lines look like, so you'll need to do that), and then you do a hash lookup to see if it's a bad port.
I used a hash here, although in this case an array would work just as well since there are only numerical indices. I believe using an array would allocate space for 0..54321 however, which is not ideal.# Build the hash my %bad_ports = (12345=>1, 12346=>1, 20034=>1, 8787=>1, 31337=>1); # s +hort list while (<FWLOG>) { my $port = extract_port_from($_); # fill in a regex here print if $bad_ports{$port}; }
I hope these techniques are useful to you! And a small warning: while I made my best effort to write working code, I didn't test it.
Alan
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
RE: RE: I want to be a Perl Jedi
by athomason (Curate) on Jul 18, 2000 at 21:59 UTC |