in reply to How can I print three lines before pattern match?

If you want to avoid loading the entire file into memory,
my @history; while (<>) { print @history if /pattern/; push @history, $_; shift @history if @history > 3; }

No direction was given for handling overlapping matches.

Replies are listed 'Best First'.
Re^2: How can I print three lines before pattern match?
by Narveson (Chaplain) on Aug 14, 2009 at 05:24 UTC

    Or if you don't want to test the length of your array forevermore:

    my @history = ("\n") x 3; while (<>) { print @history if /pattern/; push @history, $_; shift @history; }

      This works very well, thank all of you for your help.

      Where can I place a print statement that seperates the output results for each match?

      #!/Perl/bin/perl -w open(INFILE, "< file.log") or die "Cant open file : $!"; open(OUT, "> results.txt") or die "Cant open new file : $!"; use strict; my $pattern = "Error while detecting new item"; my @history = ("\n") x 3; while (<INFILE>) { print OUT @history if /$pattern/; push @history, $_; shift @history; } print $.; close INFILE; close OUT; exit;

      Example:

      results.txt matched line 1 matched line 2 matched line 3 results of first match matched line 1 matched line 2 matched line 3 results of second match and so on...

      Thank you again so much, Neurotoxx

      ++, but that should be my @history = ('') x 3;

        What does the '' vs. "\n" do?

        How could I print also the same line that has the pattern match?

        Thank you Sifu,<\p>

        Neurotoxx

        Thank you very much for your help.

        I'm sorry to bother, but how can I add the existing matched line with the three lines?

        ++, but that should be my @history = ('') x 3;
        ++, but that should be my @history = ('') x 3 + $.; #???

        Thank you agian.