in reply to Print 5 lines before and after pattern match from a list

Hello jayu_rao,

A side note: In the regular expression qr/.*Error.*/, .* means “match zero or more characters1”, so it has the same meaning as the simpler regex qr/Error/. Besides being shorter, simpler, and (IMO) clearer, the latter is also about 6% faster:

use strict; use warnings; use Benchmark qw( cmpthese ); use constant { MATCHES => 6, POWER => 14, }; my @orig = ( qr/.*Error.*/, qr/.*error.*/, qr/.*ERROR.*/, qr/.*FATAL.*/, qr/.*Critical.*/, qr/.*exception.*/, ); my @new = ( qr/Error/, qr/error/, qr/ERROR/, qr/FATAL/, qr/Critical/, qr/exception/, ); my $total = MATCHES * (2 ** POWER); my @lines = <DATA>; push @lines, @lines for 1 .. POWER; cmpthese ( 10, { orig => sub { find(\@orig, \@lines) }, new => sub { find(\@new, \@lines) }, } ); sub find { my ($res, $lines) = @_; my $count = 0; for my $line (@$lines) { $line =~ /$_/ && ++$count for @$res; } $count == $total or die "Expected $total, counted $count"; } __DATA__ Line 1 This contains an Error: 1 Line 3 Line 4 This contains an error: 2 This contains an ERROR: 3 Line 7 FATAL (4) Line 9 This problem is Critical Line 11 exception

Typical output:

13:27 >perl 1182_SoPW.pl s/iter orig new orig 1.40 -- -6% new 1.32 6% -- 13:27 >

1That is, zero or more of any character other than newline. To match newlines, an /s modifier is needed.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,