in reply to Re^2: How can I print three lines before pattern match?
in thread How can I print three lines before pattern match?

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

Replies are listed 'Best First'.
Re^4: How can I print three lines before pattern match?
by neurotoxx (Novice) on Aug 14, 2009 at 22:37 UTC

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

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

    Thank you Sifu,<\p>

    Neurotoxx

      Print the empty string prints nothing. Printing a newline prints an empty line.
      my @history = ('') x 3; while (<>) { print @history, $_ if /pattern/; push @history, $_; shift @history; }
      or
      my @history = ('') x 4; while (<>) { push @history, $_; shift @history; print @history, $_ if /pattern/; }
Re^4: How can I print three lines before pattern match?
by neurotoxx (Novice) on Aug 17, 2009 at 01:42 UTC

    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.

      Figured it out...to add the line that contains the match string, I added an additional line to the loop. Probably not the best way, but it works.

      while (<$_>) { print OUT @history if /$pattern/; print OUT $_ if /$pattern/; # adds line with match push @history, $_; shift @history; }

      Thanks again every one,

      Neurotoxx

        Probably not the best way

        Indeed. You perform the regex match twice for nothing. The two previously submitted solutions are better. -- for asking for help then ignoring the answers twice.