Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: get n lines before or after a pattern

by Athanasius (Chancellor)
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.”

HTH,

Athanasius <°(((><contra mundum

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://983761]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2017-12-11 23:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What programming language do you hate the most?




















    Results (319 votes). Check out past polls.

    Notices?