http://www.perlmonks.org?node_id=983761


in reply to get n lines before or after a pattern

Here is another approach, using Tie::File:

#! perl use strict; use warnings; use Tie::File; my $file = 'test.txt'; tie my @lines, 'Tie::File', $file or die "Cannot tie file '$file': $!" +; for my $i (0 .. $#lines) { if ($lines[$i] =~ m{ \b jack \b }x) { for ($i - 2 .. $i) { print $lines[$_], "\n" unless $_ < 0; } for (my $found = 0; !$found && $i <= $#lines; ++$i) { if ($lines[$i] =~ m{ \b lastname \b }x) { print $lines[$i], "\n"; $found = 1; } } } } untie @lines;

What is nice about this approach is that, by treating the data file as an ordinary array, it is possible to meet more complicated requirements without the programming overhead of manually maintaining line buffers. So, this approach has the advantage of being scalable. Some notes on Tie::File:

HTH,

Athanasius <°(((><contra mundum