develooper Front page | perl.beginners | Postings from March 2002

Re: How to insert a line in the middle of a file?

Thread Previous | Thread Next
Eric Beaudoin
March 4, 2002 11:25
Re: How to insert a line in the middle of a file?
Message ID:
At 14:11 2002.03.04, Kypa, J. (Jagan) wrote:
>$old = "$LeafPreName.acf";
>$new = "$old".".tmp";
>$bak = "$old".".orig";
>open(OLD, "<$old");
>open(NEW, ">$new");
>while (<>) {
>   if ($. == 3) {
>   print NEW "INTEGRATOR/ ERROR=5.0E-2, HINIT=2.5E-4,HMAX=2.5E-4,
>KMAX=6, MAXIT=10\n";
>                }

The <> read fro STDIN or the files that you give as parameter to the script (one after the other). You open OLD but never read it... Also, you need to print every lines to NEW, net just the third one.

So your while loop should be:

while (<OLD>) {
    print NEW "INTEGRATOR/ ERROR=5.0E-2, HINIT=2.5E-4,HMAX=2.5E-4, KMAX=6, MAXIT=10\n"
      if ($. == 3);
    print NEW;  # Print $_ to NEW. 

As a bonus, when there is only one expression with the if, you can put it in one line.

Hope this helps.

√Čric Beaudoin               <>

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About