Let's say I wanted to find the word 'banana' in a file, then add a line later, such that there were three lines between the 'banana' line and my new line. I could do this:
#!/usr/bin/env perl
use 5.010; use warnings; use strict;
while(<DATA>){
print; # print the line
if(/banana/){ # if it contained banana
print scalar <DATA> for 1..3; # print the next three lines
print "This line was added.\n"; # then add the new line
}
} # then print the rest of the
+lines
__DATA__
a is for apple
b is for banana
c is for cantaloupe
d is for dill
e is for elderberry
f is for fennel
g is for grapefruit
h is for honeydew
You should be able to adapt that for your needs. For production code, you'd want to add something to handle the case where there aren't three lines between 'banana' and the end of the file, but since this looks like a homework assignment, I'll assume that's not necessary. Another improvement would be to make the search word and the number of lines to skip arguments set with variables at the top of the problem or taken from the command line. You could also write it as a subroutine which takes the input filename/filehandle, search word, and number of lines as arguments.
Aaron B.
Available for small or large Perl jobs and *nix system administration; see my home node.
-
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.
|