in reply to Reading nth line from a file

open(FH,"test.txt");
$i=0;
$j1=0;
$j2=0;
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/ ){
                $j1=-4;
        }
        elsif ( $j1<0 ){
                $j1++;
                print $_ if $j1==0;
        }
        ## If the line matches for this pattern, I should read 2nd line from current line
        elsif ( $_ =~/you have to read the second line/ ){
                $j2=-2;
        }
        elsif ( $j2<0 ){
                $j2++;
                print $_ if $j2==0;
        }
print $i++,"\n";


Replies are listed 'Best First'.
Re^2: Reading nth line from a file
by gmontema (Initiate) on Dec 19, 2008 at 18:42 UTC
    sorry disregard the previous message.

      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