In the first code example, all you're doing is modifying the contents of $_ in the while loop, and then not bothering to do anything with it. In the second example...

open (OUTFILE, "<$dirContent");

You just opened your "out file" for reading. You wanted...

open (OUTFILE, ">$dirContent");

Worse still... You're opening the same file twice! You have two choices for what you want to do... Either open the original file for reading, and a new one for writing, then rename the new to the old when you're done, or better still, do this all from the command line (which will basically do the same thing under the hood.

perl -p -i.bak -e '/oldstring/newstring/'

Having to write a whole new file may seem unfortunate and inefficient, but you don't really have much choice. A file is a contiguous block of bytes, and if you grow or shrink a piece of it, you basically have to shift all the following pieces around, or rewrite the whole file. The only way around rewriting the whole file is to have a file of fixed record lenghts, or to store modification information at the end of the file, and have a very dynamic, on the fly type of data extraction occuring. The latter is how a lot of text editors work, recording lots of small changes at the end of the file, and every now and again performing a monolithic clean up and synchronization.


In reply to Re: replacing in file by skyknight
in thread replacing in file by jc23

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.