Perl:How to insert a line to a file.

Hi, Perl is new to me. I am trying to insert a line to a file.
Example: I have a file (trial.txt), content:

ZZZZ
AAA
DDDD

I am trying to insert CCC below AAA.
MY perl command:

open (FILE,"+>>C:\\Documents and Settings\\trial.txt\n")|| die "can't open file"; 
while(<FILE>) 
{         
    if(/AAA/) 
   { 
     print FILE "CCC\n";  
    } 
}#end while 
close(FILE); 

The output I get:

ZZZZ
AAA
DDDD
ZZZZ
AAA
CCC

Where else what I need is:

ZZZZ
AAA
CCC
DDDD

It appends the whole file again and replaces the next line after AAA with CCC, where else what I need is to insert CCC in the existing file below AAA. Thanks to advise. :slight_smile:

Im afraid you cannot simply insert lines into a file in this manner - you have to either read the whole file into memory and write back the new file, or you have to write the output to a temporary file.
Here is an example of the former...

#!/usr/bin/perl
open(FILE,"foo.txt") || die "can't open file for read\n"; 
my @lines=<FILE>;
close(FILE);
open(FILE,">foo.txt")|| die "can't open file for write\n";
foreach $line (@lines) {
    if($line =~ /AAA/) {
        print FILE "CCC\n";
    } else {
        print FILE $line;
    }
}#end foreach
close(FILE);

Thanks citaylor :).. tried applying your example, but it still replaces the AAA with CCC, instead of adding the CCC below AAA. Meanwhile, I am trying to google for any tips on this, no luck so far..

Sorry, I misunderstood...

#!/usr/bin/perl
open(FILE,"foo.txt") || die "can't open file for read\n"; 
my @lines=<FILE>;
close(FILE);
open(FILE,">foo.txt")|| die "can't open file for write\n";
foreach $line (@lines) {
    print FILE "CCC\n" if($line =~ /AAA/);
    print FILE $line;
}#end foreach
close(FILE);

If you want AAA after CCC, then these two lines need to be swapped

    print FILE "CCC\n" if($line =~ /AAA/);
    print FILE $line;

Here ..

#!/usr/bin/perl -w
open(IFILE,"<test.abc") || die "can't open file for read\n"; 
open(OFILE,">abc.out") || die "can't open file for writing\n"; 
while (<IFILE>){
     if(/AAA/) {
        print OFILE $_;
        print OFILE "CCC\n";
    }else {
        print OFILE $_;
}
}
close(IFILE);
close(OFILE); 
$ cat test.abc 
ZZZZ
AAA
DDDD
$ cat abc.out 
ZZZZ
AAA
CCC
DDDD

Got it now... :slight_smile: