in reply to Re^2: Reading nth line from a file
in thread Reading nth line from a file

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