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

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

Thread Previous
From:
jkypa
Date:
March 4, 2002 11:55
Subject:
Re: How to insert a line in the middle of a file?
Message ID:
200203041955.g24Jt8j24501@dymwsm09.mailwatch.com
Eric, 
	Thank you. Works like a charm. Thanks again. I have the loop as 

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

Regards,
Jagan

Eric Beaudoin wrote:
> 
> 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>

-- 
Thank you,
Jagan Kypa

ADAMS/Pre Technical Support
Vehicle Dynamics Group
313-621-6510

Thread Previous


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