in reply to how to read multiple line from a file

If you really need a line-based approach rather than just loading the whole thing into memory (most of the time, the latter approach will work just fine), then you need to cache the previous lines and do a search of the cache:
use strict; use warnings; my $csize = 2; ### Number of lines to save my (@cache, $str, $c); my $file = 'data.txt'; open (IN, $file) or die "Can't open $file for read."; while (<IN>) { shift @cache if $#cache == $csize - 1; push @cache, $_; $c++; $str = join '', @cache; if ($str =~ /jumped\nover/) { print "String found in $file at lines " . ($c - $#cache) . "-$ +c:\n"; print $str; last; } }
Input file data.txt:
the quick brown fox jumped over the unfortunate dog
Output:
String found in data.txt at lines 5-6: jumped over

Replies are listed 'Best First'.
Re^2: how to read multiple line from a file
by educated_foo (Vicar) on Apr 13, 2013 at 13:27 UTC
    Just a minor note from the C programmer in me: the easiest and most efficient way to do a fixed-size queue is to use the mod operator:
    while (<>) { $buf[$. % $size] = $_; }
      As a minor note of a functional programmer, I'll put the logic in an extra iterator like here: Re: Split string after 14 Line Feeds?.

      This makes the code much more readable. =)

      Otherwise I'm not sure where you want the processing logic to happen in your code, maybe something like unless ($. % $size) { ...} within the loop?

      I think If a sliding window is needed, shift and push might be better.

      Cheers Rolf

      ( addicted to the Perl Programming Language)

        If a sliding window is needed, shift and push might be better.
        This leads to extra memmove()s if you're lucky (I believe Perl does this), and endless memory consumption otherwise. If you use the mod operator when indexing your array, you get a ring buffer without excess copying. You could probably abstract this out nicely with a bit of extra work.
        Just another Perler interested in Befunge Programming.
      How does this adapt to variable length records/lines/data?

      If you didn't program your executable by toggling in binary, it wasn't really programming!

        It keeps a fixed number of records (as defined by $/). Length has nothing to do with it.
Re^2: how to read multiple line from a file
by skyworld_chen (Acolyte) on Apr 13, 2013 at 11:59 UTC
    thanks for all of your replies. I will check these ideas again.