open(FH,"test.txt");
my $i=0;
my @p =();
while ( <FH> ) {
        ## If the line matches for this pattern, I should read 4th line from current line
        if ( $_ =~/you have to read the fourth line/ ){
                push @p,$i+4;
        }
        ## If the line matches for this pattern, I should read 2nd line from current line
        elsif ( $_ =~/you have to read the second line/ ){
                push @p,$i+2;
        }
        @p=sort(@p);
        foreach my $j(@p){print $_ if $j==$i; shift @p if $j<=$i;} 
$i++;


Input:
first line 1
second line 2
third line 3
you have to read the fourth line
one 5
two
three 7
four
five 9
six 6
you have to read the second line
one 12
two
three 13
first line 14
second line 15
third line 16
you have to read the fourth line
you have to read the second line
one 20
two with in a four
four with two inside
five 23
six 24
three 25
you have to read the second line
you have to read the fourth line
two with a for
two 29
three 30
four in a two
ten 32
one 33

Output:
four
two
two with in a four
four with two inside
two with a for
four in a two


In reply to Re^3: Reading nth line from a file by gmontema
in thread Reading nth line from a file by perlthirst

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.