perlthirst has asked for the wisdom of the Perl Monks concerning the following question:
I am having one program, which read a line by line from a file, if the line matches for the particular pattern, then i should read nth line from a current line.
some simple example is:
open(FH,"test.txt"); while ( <FH> ) { ## If the line matches for this pattern, I should read 4th lin +e from current line if ( $_ =~/you have to read the fourth line/ ){ $i=0; while ($i<4) { $line = <FH>; $i++; } print $line; } ## If the line matches for this pattern, I should read 2nd lin +e from current line elsif ( $_ =~/you have to read the second line/ ){ $i=0; while ($i<2) { $line = <FH>; $i++; } print $line; } }
Input:
first line
second line
third line
you have to read the fourth line
one
two
three
four
five
six
you have to read the second line
one
two
three
output:
four
two
The above coding works for me for my requirement
but i felt that the way that i have handled to read nth line from a file, is inefficient.. kindly advice some efficient way to do the above.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Reading nth line from a file
by jwkrahn (Abbot) on Dec 19, 2008 at 05:53 UTC | |
|
Re: Reading nth line from a file
by brsaravan (Scribe) on Dec 19, 2008 at 06:15 UTC | |
by perlthirst (Scribe) on Dec 19, 2008 at 06:44 UTC | |
|
Re: Reading nth line from a file
by NetWallah (Canon) on Dec 19, 2008 at 06:32 UTC | |
|
Re: Reading nth line from a file
by imrags (Monk) on Dec 19, 2008 at 07:25 UTC | |
|
Re: Reading nth line from a file
by Bloodnok (Vicar) on Dec 19, 2008 at 12:47 UTC | |
|
Re: Reading nth line from a file
by gmontema (Initiate) on Dec 19, 2008 at 18:41 UTC | |
by gmontema (Initiate) on Dec 19, 2008 at 18:42 UTC | |
by gmontema (Initiate) on Dec 22, 2008 at 23:31 UTC |