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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|