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
From:
Eric Beaudoin
Date:
March 4, 2002 11:25
Subject:
Re: How to insert a line in the middle of a file?
Message ID:
5.1.0.14.2.20020304142011.00ad62a0@pop.videotron.ca
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";
>                }
>}
>close(OLD);
>close(NEW);
>
>rename($old,$bak);
>rename($new,$old);

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               <mailto:beaudoer@videotron.ca>


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About