Hi folks, I'm looking to read in a file, search for a particular string and then pring the nth line before the line containing the match. The code below which prints lines before and after the match are getting to where I want to be, but I'm looking for something cleaner/easier or other better approaches to this. Thanks in advance!
use strict; use warnings; use Tie::File; sub max ($$) { $_[$_[0] < $_[1]] } sub min ($$) { $_[$_[0] > $_[1]] } my $file_in = 'data.txt'; my @lines; tie @lines, 'Tie::File', $file_in or die "Unable to tie $file_in $!"; my $n_recs = @lines; # how many records are in the file? my @lnbrs = (); my $i = 0; while ($i < $n_recs - 1) { my $twolines = $lines[$i] . $lines[$i + 1]; if ($twolines =~ m/file\s+for\s+(?:bankrup|chapter)/im) { push @lnbrs, $i } $i++; } foreach my $ln (@lnbrs) { my $start = max($ln-3, 0); my $end = min ($ln+3, $n_recs); <strong class="highlight">print</strong> '-' x 75, "\n"; foreach ($start .. $end) { <strong class="highlight">print</strong> "$lines[$_]\n"; } } untie @lines;

In reply to find a match and pull nth line before the match by msensay

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.