How to insert a line to a file.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SGKT
    New Member
    • Dec 2010
    • 1

    How to insert a line to a file.

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

    I am trying to insert CCC below AAA.
    MY perl command:
    Code:
    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 ouuput I get:
    ZZZZ
    AAA
    DDDDZZZZ
    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. :)
    Last edited by numberwhun; Dec 9 '10, 12:57 AM. Reason: Please use code tags!
  • rovf
    New Member
    • May 2010
    • 41

    #2
    You are trying to read and write from the same file. Plus, it is a text file. This is asking for trouble.

    I suggest that you create a new file (with the lines inserted), and after you are done, move the new file to the old one.

    Comment

    Working...