Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical

Re: get n lines before or after a pattern

by Athanasius (Bishop)
on Jul 26, 2012 at 03:32 UTC ( #983761=note: print w/replies, xml ) Need Help??

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:

  • It’s a core module: Tie::File
  • Written by Dominus
  • From the docs: “The file is not loaded into memory, so this will work even for gigantic files.”


Athanasius <°(((><contra mundum

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://983761]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (4)
As of 2018-09-20 03:17 GMT
Find Nodes?
    Voting Booth?
    Eventually, "covfefe" will come to mean:

    Results (171 votes). Check out past polls.

    • (Sep 10, 2018 at 22:53 UTC) Welcome new users!