use strict; use warnings; use Benchmark qw(cmpthese); my $fileName = "data1"; my $string = $ARGV[0] || die "\nNo Search String Provided.$!\n\n"; my $stringRegex = qr{$string}; my $headerRegex = qw{^Header}; ## Match Headers my $greenRegex = qr{(^Header).*)}; my $redRegex = qr{($string)}; cmpthese (1, { case1 => sub {&case1}, case2 => sub {&case2}, }, ); sub case1 { my $matches = `grep -h -F -C50 '$grepString' $fileName`; my $match; my $data; my $header; for (split /^/, $matches) { ## More efficient than array? (Scalars use less memory) if ($_ =~ $headerRegex) { ## Match headers if ($match) { $data =~ s/$greenRegex/\033[1;32m$1\033[m/o; ## Color headers in GREEN $data =~ s/$redRegex/\033[1;31m$1\033[m/go; ## Color string matches in RED $data =~ s/\n\n/\n/go; ## Remove double blanks lines print $data, "\n"; $match = 0; } $data = ""; $header = 1; } if (($header) && (0 > index ($_, $string))) { ## Match body of section $data .= $_; } elsif ($header) { ## Match search string $data .= $_; $match = 1; } } } sub case2 { open(my $fh, '<', "$fileName") or die $!; my $match; my $data; my $header; while (<$fh>) { if ($_ =~ $headerRegex) { if ($match) { $data =~ s/$greenRegex/\033[1;32m$1\033[m/o; $data =~ s/$redRegex/\033[1;31m$1\033[m/go; $data =~ s/\n\n/\n/go; print $data, "\n"; $match = 0; } $data = ""; $header = 1; } if (($header) && (0 > index ($_, $string))) { $data .= $_; } elsif ($header) { $data .= $_; $match = 1; } } } case1 4.79 s/iter case2 46.6 s/iter